2011-11-30 28 views
2

我有一個如何使這個活動記錄協會

項目模型

class Item < ActiveRecord:Base 
    has_and_belongs_to_many :orders 
end 

而且訂單模型

class Order < ActiveRecord:Base 
    has_and_belongs_to_many : items 
end 

一個訂單可以有很多項目,其中HABTM會照顧的。但是,我在哪裏/如何儲存正在訂購的物品的數量?

例如: 可以說Order1中有Item1和Item2。現在我想存儲與項目相關的數量,如Order1有兩個Item1和五個Item2。

什麼是軌道的方式來做到這一點?

回答

2

你可以做到這一點的一種方法是使用has_many:through關聯。這會爲訂單和項目之間的連接表創建一個獨立的實體。在你的情況下:

class Order < ActiveRecord::Base 
    has_many :invoices 
    has_many :items, :through => :invoices 
end 

class Invoice < ActiveRecord::Base 
    belongs_to :order 
    belongs_to :items 

    #Put in the migration for this table a column for quantity 
end 

class Item < ActiveRecord::Base 
    has_many :invoices 
    has_many :orders, :through => :invoices 
end 

這將解決你的問題,我相信。這樣,與Item1相關聯的Order1在發票表中的數量爲2,而在發票表中具有單獨數量爲5的Item2的數量相同。

您可以在A Guide to Active Record AssociationsThe has_many :through Association部分了解關於這些關係的更多信息。