2

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!

R. Yanchuleff
  • 323
  • 1
  • 15

2 Answers2

2

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.

Mörre
  • 5,699
  • 6
  • 38
  • 63
1

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
oliverbarnes
  • 2,111
  • 1
  • 20
  • 31
  • Yes, sorry, my terminology was a bit obtuse, I'm trying to create a view which allows my user to add items to their store through a singular field. So say a combobox that has all the items (both products and services), and so I was trying to figure out how to model that. It sounds like this association will do what I need. – R. Yanchuleff Mar 02 '11 at 15:53
  • If i understand this correctly, I'll be able to do storeObj.inventory_items.count and get the total number of products and services in the store because of the join model? or more importantly, I can print say an invoice of all products and services by doing something like print_invoice_store_path(@inventory_items)? – R. Yanchuleff Mar 02 '11 at 15:54
  • regarding store.inventory_items.count, yeah, as with any has_many association. re print_invoice_store_path, that might be worth asking separately, but in principle yes as well. I'd imagine it more like print_invoice_store_path(@store) though, and then you could access @store.inventory_items within the action. in any case, the associated collection will be available for you to process or output anyway you like – oliverbarnes Mar 02 '11 at 21:01
  • re the combobox intention, yes this should work for it. I didn't find the question obtuse :) Having a clear picture of an interface and what you're trying to accomplish does help a lot though. – oliverbarnes Mar 02 '11 at 21:07