Rails 3 Abstract Class vs Inherited Class
In my rails 3 model, I have two classes: Product, Service. I want both to be of type InventoryItem because I have another model called Store and Store开发者_开发知识库 has_many :InventoryItems
This is what I'm trying to get to, but I'm not sure how to model this in my InventoryItem model and my Product and Service models. Should InventoryItem just be a parent class that Product and Service inherit from, or should InventoryItem be modeled as a class abstract of which Product and Service extend from.
Thanks in advance for the advice!
Personally, I would not use inheritance. Why don't you just say
has_many :services
has_many :products
Inheritance is pretty expensive - both in terms of runtime and often in readability too. This case sounds like a very basic case for which no inheritance is required. Do you really want products and services to actually INHERIT something from a base class? What you writes indicates all you want is to establish the association.
I'd use neither, and follow what Mörre suggested to have InventoryItem be a join model:
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
精彩评论