是否可以为数组类创建一个属性?我尝试阅读this https://stackoverflow.com/questions/3438827/ruby-model-with-an-array-as-an-attribute但我并没有从中得到太多。我想做这样的事情:
class CreateArches < ActiveRecord::Migration
def change
create_table :arches do |t|
t.string :name
t.array :thearray
t.timestamps
end
end
end
这样当我在 Arch 实例上调用 .thearray 时,我会得到一个可以添加新元素的数组。
ruby-1.9.2-p290 :006 > arc = Arch.new
ruby-1.9.2-p290 :007 > arc.thearray
=> []
创建带有文本字段的模型
> 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) ==========================================
编辑模型以使字段序列化为数组
class Arches < ActiveRecord::Base
serialize :thearray,Array
end
测试一下
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"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)