質問

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!

正しい解決策はありません

他のヒント

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top