Rails:跳过两个belongs_to关联

时间:2012-12-11 13:38:12

标签: ruby-on-rails

说我有三个型号......

Product
 belongs_to :ProductCategory
 belongs_to :Manufacturer

ProductCategory
 has_many :products

Manufacturer
 has_many :products

我想通过类似product_category.manufacturers的调用,询问ProductCategory的实例,以获取该ProductCategory中的产品制造商。

我目前在Products模型中实现了它:

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

有没有更好的“轨道方式”?

谢谢!

1 个答案:

答案 0 :(得分:2)

是的,这是一个解决得非常好的问题,也是在Rails中使用Associations的基本基本部分。你想要has_many :through

class ProductCategory
  has_many :products
  has_many :manufacturers, :through => :products
end