Why can't I create an array as a column in a t

2020-03-04 03:22发布

问题:

Why can't I do something like this:

class CreateModels < ActiveRecord::Migration
  def self.up
    create_table :fruit do |t|
      t.array :apples
    end
  end
end

Is there some other way to make an array ("apples) be an attribute of an instance of the Fruit class?

回答1:

Check out the Rails guide on associations (pay particular attention to has_many).

You can use any column type supported by your database (use t.column instead of t.type), although if portability across DBs is a concern, I believe it's recommended to stick to the types explicitly supported by activerecord.

It seems kind of funny for fruit to have_many apples, but maybe that is just an example? (I would expect apples to be a subclass of fruit).



回答2:

In Rails 4 and using PostgreSQL you can actually use an array type in the DB:

Migration:

class CreateSomething < ActiveRecord::Migration
  def change
    create_table :something do |t|
      t.string :some_array, array: true, default: []
      t.timestamps
    end
  end
end


回答3:

You may use serialize. But if an Apple is going to be an AR object, use associations.