Question

Say I have three models...

Product
 belongs_to :ProductCategory
 belongs_to :Manufacturer

ProductCategory
 has_many :products

Manufacturer
 has_many :products

I'd like to ask an instance of ProductCategory for the set of Manufacturers for Products in that ProductCategory with a call like product_category.manufacturers.

I've currently implemented it in the Products model like this:

def manufacturers
  Manufacturer.find(self.products.pluck(:manufacturer_id).uniq.to_a
end

Is there a better "rails way"?

Thanks!

No correct solution

OTHER TIPS

Yes, this is an extremely well-solved problem and a fundamentally basic part of using Associations in Rails. You want has_many :through:

class ProductCategory
  has_many :products
  has_many :manufacturers, :through => :products
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top