阵列属性为Ruby型号 [英] Array Attribute for Ruby Model

查看:116
本文介绍了阵列属性为Ruby型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能创建一个类是数组属性?我试着阅读,但我没有得到太多了它。我想要做这样的事情:

 类CreateArches< ActiveRecord的::迁移
  高清变化
    CREATE_TABLE:拱门做| T |
      t.string:名称
      t.array:thearray
      t.timestamps
    结束
  结束
结束

这样,当我打电话.thearray拱的一个实例,我得到一个数组,我可以添加新的元素。

 红宝石1.9.2-P290:006>圆弧= Arch.new
红宝石1.9.2-P290:007> arc.thearray
 = GT; []


解决方案

创建一个文本字段的模型

 >导轨G型拱门thearray:文本
  调用active_record
  建立DB /迁移/ 20111111174052_create_arches.rb
  创建应用程序/模型/ arches.rb
  调用test_unit
  创建测试/单位/ arches_test.rb
  创建测试/夹具/ arches.yml
>耙分贝:迁移
== CreateArches:迁移============================================= ======
- CREATE_TABLE(:拱门)
    - > 0.0012s
== CreateArches:迁移(0.0013s)========================================= =

编辑模型,使该领域的序列化到一个数组

 类拱门< ActiveRecord的::基地
  连载:thearray,阵列
结束

测试了

 红宝石1.8.7-P299:001〕 A = Arches.new
 = GT; #<拱门ID:无,thearray:[],created_at:无,的updated_at:无>
红宝石1.8.7-P299:002> a.thearray
 = GT; []
红宝石1.8.7-P299:003> a.thearray<< 测试
 = GT; [测试]

Is it possible to create an attribute for a class that is an array? I tried reading this but I didn't get much out of it. I want to do something like this:

class CreateArches < ActiveRecord::Migration
  def change
    create_table :arches do |t|
      t.string :name
      t.array :thearray
      t.timestamps
    end
  end
end

such that when I call .thearray on an instance of Arch I get an array that I can add new elements to.

ruby-1.9.2-p290 :006 > arc = Arch.new
ruby-1.9.2-p290 :007 > arc.thearray
 => [] 

解决方案

Create a model with a text field

> rails g model Arches thearray:text
  invoke  active_record
  create    db/migrate/20111111174052_create_arches.rb
  create    app/models/arches.rb
  invoke    test_unit
  create      test/unit/arches_test.rb
  create      test/fixtures/arches.yml
> rake db:migrate
==  CreateArches: migrating ===================================================
-- create_table(:arches)
   -> 0.0012s
==  CreateArches: migrated (0.0013s) ==========================================

edit your model to make the field serialized to an array

class Arches < ActiveRecord::Base
  serialize :thearray,Array
end

test it out

ruby-1.8.7-p299 :001 > a = Arches.new
 => #<Arches id: nil, thearray: [], created_at: nil, updated_at: nil> 
ruby-1.8.7-p299 :002 > a.thearray
 => [] 
ruby-1.8.7-p299 :003 > a.thearray << "test"
 => ["test"] 

这篇关于阵列属性为Ruby型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆