配列であるクラスの属性を作成することは可能ですか?読んでみましたこれしかし、あまり成果は得られませんでした。次のようなことをしたいのです。
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
=> []
ベストアンサー1
テキストフィールドを持つモデルを作成する
> 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"]