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

泪湿孤枕 提交于 2019-11-30 21:01:11

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).

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!