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
문제
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