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
=> []
While you can use a serialized array as tokland suggested, this is rarely a good idea in a relational database. You have three superior alternatives:
has_manyrelationship.composed_of.has_manys, you might want to investigate a DB that actually supports array fields. PostgreSQL does this (and array fields are supported in Rails 4 migrations), but you might want to use either a non-SQL database like MongoDB or object persistence such as MagLev is supposed to provide.If you can describe your use case — that is, what data you’ve got in the array — we can try to help figure out what the best course of action is.