2011-03-02 111 views
2

在我的Rails 3的模式,我有兩個類:產品,服務。我想這兩個是類InventoryItem的,因爲我有另一種模式叫做商店和商店的has_many:InventoryItems的Rails 3抽象類VS繼承

這就是我想要去的,但我不知道如何在我的InventoryItem模擬這種和我的產品和服務模型。 InventoryItem是否應該是產品和服務繼承的父類,或者是否應該將InventoryItem建模爲產品和服務擴展的類摘要。

在此先感謝您的意見!

回答

1

我既不使用,並遵循什麼Mörre建議有InventoryItem是加盟模式:

class Store 
    has_many :inventory_items 
    has_many :products, :services, :through => :inventory_items 
end 

class InventoryItem 
    belongs_to :store 
    belongs_to :products, :services 
end 

class Product 
    has_many :inventory_items 
    has_many :stores, :through => :inventory_items 
end 

class Service 
    has_many :inventory_items 
    has_many :stores, :through => :inventory_items 
end 
+0

是的,對不起,我的術語有點鈍,我試圖創建一個視圖,允許我的用戶通過單個字段將商品添加到他們的商店。所以說一個包含所有項目(包括產品和服務)的組合框,所以我試圖找出如何建模。這聽起來像這個協會會做我所需要的。 – 2011-03-02 15:53:59

+0

如果我理解正確這,我就可以做storeObj.inventory_items.count和獲得的產品和服務的總人數在店裏,因爲加盟模式?或者更重要的是,我可以通過執行類似print_invoice_store_path(@inventory_items)的方式打印所有產品和服務的發票。 – 2011-03-02 15:54:27

+0

關於store.inventory_items.count,是的,與任何has_many關聯一樣。重新print_invoice_store_path,這可能值得單獨詢問,但原則上也是如此。我想像它更像print_invoice_store_path(@store)雖然,那麼你可以在行動中訪問@ store.inventory_items。在任何情況下,相關的系列將於以便您進行處理或輸出反正你喜歡 – oliverbarnes 2011-03-02 21:01:24

2

就個人而言,我不會用繼承。你爲什麼不只是說

has_many :services 
has_many :products 

繼承是相當昂貴的 - 無論是在運行方面,往往可讀性了。這種情況聽起來像一個非常基本的情況,不需要繼承。你真的想要產品和服務實際上INHERIT基類的東西嗎?你寫什麼表明你想要的是建立關聯。