Topic: has_many :distant_relatives

I have some associations:

Product belongs_to :category ; Category has_many :products
ProductOptionSet belongs_to :category ; Category has_many :product_option_sets
ProductOption belongs_to :product_option_set ; ProductOptionSet has_many :product_options

I would like to get at all of the ProductOptions available to a given Product. So I would need to do something like (not valid code, but you get the idea)

How would I connect Product directly to ProductOptions so that I could just do

Last edited by jed.hurt (2006-11-18 21:21:47)

I thought about how mothers feed their babies with tiny little spoons and forks, so I wondered what do Chinese mothers use. Toothpicks?

Re: has_many :distant_relatives

You've already got the three classes pretty well outlined.  There's just one line you need to add to your Product class and one to your Category class to get what you want:

class Product < ActiveRecord::Base
  belongs_to :category
  # here's the trick:
  has_many :product_options, :through => :category
class Category < ActiveRecord::Base
  has_many :products
  has_many :product_option_sets
  # and that trick again:
  has_many :product_options, :through => :product_option_sets

I haven't tested it so you might need to tweak some things, but that's the idea.  If you don't want to do anything that fancy you can always just add a method in Product called 'product_options' that calls 'category.product_options' and add a 'product_options' method in Category that returns 'product_option_sets.product_options'.  Then you'd have to do some uniq'ing to remove duplicates.