2012-08-14 88 views
0

我只是想知道如果有人能向我解释如何在两个对象之间创建关系(编程示例会有帮助,所以我可以在rails控制台中测试),其中关系定义为has_many:通过它具有附加属性。这些对象定义如下:通过关系指定has_many属性

class Item < ActiveRecord::Base 
    has_many :collections, :through => :collection_items 
end 

class Collection < ActiveRecord::Base 
    has_many :items, :through => :collection_items 
end 

class CollectionItem < ActiveRecord::Base 
    belongs_to :collection 
    belongs_to :item 

    attr_accessible :collection_id, :item_id, :quantity 
end 

回答

1

试试这个:

CollectionItem.create(item_id: Item.first, collection_id: Collection.first, quantity: 999) 

就在 'Item.first' 和 'Collection.first' 替换为任何逻辑你必须得到正确的项目和收集。

+0

好的,所以在这种情况下,我们创建了关系对象,而不是将其中一个成员添加到另一个集合中(集合可能在我的示例类中使用的名称很糟糕,指的是这里的对象集合,集合)? – binarymelon 2012-08-14 13:45:01

+1

好吧,我想你也可以写下如下内容:'Item.collectionItems.create(数量:999,collection_id:Collection.first)'。 – davidrac 2012-08-14 13:51:53