2011-03-02 113 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基类的东西吗?你写什么表明你想要的是建立关联。