2012-08-14 158 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