Rails 3抽象类与继承类

时间:2011-03-02 15:03:57

标签: ruby-on-rails ruby-on-rails-3 inheritance abstract-class

在我的rails 3模型中,我有两个类:Product,Service。我希望两者都是InventoryItem类型,因为我有另一个名为Store and Store has_many的模型:InventoryItems

这是我想要的,但我不确定如何在我的InventoryItem模型和我的产品和服务模型中对此进行建模。 InventoryItem应该是Product和Service继承的父类,还是InventoryItem应该被建模为产品和服务扩展自的类摘要。

提前感谢您的建议!

2 个答案:

答案 0 :(得分:2)

就个人而言,我不会使用继承。你为什么不这么说

has_many :services
has_many :products

继承非常昂贵 - 无论是在运行时还是在可读性方面。这种情况听起来像一个非常基本的情况,不需要继承。您是否真的希望产品和服务能够从基类中实现INHERIT?你写的内容表明你想要的就是建立联想。

答案 1 :(得分: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
相关问题