Here is an example of the structure I’m trying to achieve. I’ll just setup a silly example so it’s easier to explain:
Let’s say we have a Product that holds a bunch of different hammers. Each hammer has multiple attributes (weight, size, color, etc) but they all can hammer nails in. So in that respect they are interchangeable. However they are not interchangeable with other products, like a chainsaw or a sledgehammer.
So I want to be able to keep a list of all products that are interchangeable. So if one hammer is not available I could see ids all the other products that I can give to a customer instead.
Since I don’t know how many interchangeable products each product can have ( let’s say there are 5 different hammers, and 50 screwdrivers), I can’t just create an interchangeable field to keep this info. i was thinking about enums, but they are more complicated to run reports on.
Here is what I have so far, but I’m not sure if this is the best solution (it’s kind of late and my mind is starting to melt – this is a much simplified example if my self referential tables):
class Product < ActiveRecord::Base
has_many :interchangable_products, :dependent => :destroy
end
class InterchangableProduct < ActiveRecord::Base
belongs_to :product, :class => "Product", :foreign_key => :product_id
belongs_to :interchangable_with, :class_name => "InterchangableProduct", :foreign_key => :interchangable_with_id
has_many :interchangables, :class_name => "InterchangableProduct", :inverse_of => :interchangable_with, :foreign_key => :interchangable_with_id
validates :product_id, :presence => true, :uniqueness => [:scope => :interchangable_with_id]
end
Thank you
Thanks to a comment from Dave Newton I arrived to a solution that looks sort of like this:
Hopefully this will be helpful to someone.