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?
是否有其他方法可以使数组(“apples”)成为Fruit类实例的属性?
3 个解决方案
#1
1
Check out the Rails guide on associations (pay particular attention to has_many).
查看关于关联的Rails指南(特别注意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.
您可以使用数据库支持的任何列类型(使用t.column而不是t.type),但如果担心跨DB的可移植性,我相信建议坚持使用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
17
In Rails 4 and using PostgreSQL you can actually use an array type in the DB:
在Rails 4中并使用PostgreSQL,您实际上可以在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
2
You may use serialize. But if an Apple is going to be an AR object, use associations.
您可以使用序列化。但如果Apple将成为AR对象,请使用关联。
#1
1
Check out the Rails guide on associations (pay particular attention to has_many).
查看关于关联的Rails指南(特别注意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.
您可以使用数据库支持的任何列类型(使用t.column而不是t.type),但如果担心跨DB的可移植性,我相信建议坚持使用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
17
In Rails 4 and using PostgreSQL you can actually use an array type in the DB:
在Rails 4中并使用PostgreSQL,您实际上可以在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
2
You may use serialize. But if an Apple is going to be an AR object, use associations.
您可以使用序列化。但如果Apple将成为AR对象,请使用关联。