1

我有Category模型,在哪里放置产品。每个产品都属于制造商(也有没有设置制造商的产品——这些我想标记为“未知”)。

这是我的模型:

class Product < ActiveRecord::Base
  belongs_to :manufacturer
  belongs_to :category
end

class Manufacturer < ActiveRecord::Base
  has_many :products
end

class Category < ActiveRecord::Base
  has_ancestry
  has_many :products
end

这是一个简单的查询,我如何从各个类别中获取产品:

@products = @category.products.paginate(:page => params[:page], :per_page => 15)

我想打印所有具有相应类别产品的制造商...我在这部分苦苦挣扎了半天,仍然找不到查询...

你能帮我吗,拜托,这部分?

谢谢!

4

2 回答 2

2

将此添加到您的类别模型中:

has_many :manufacturers, :through => :products

然后你可以打电话

@category.manufacturers

有关该选项的更多信息,请查看has_many的文档。through

于 2012-08-06T09:38:33.397 回答
1

你可以试试这个:

Manufacturer.where(id: @category.products.map(&:manufacturer_id).uniq)

或者我们可以依靠数据库来获取唯一值,这在大表上应该更快:

Manufacturer.where(id: Product.select("DISTINCT manufacturer_id").
  where(category: @category).map(&:manufacturer_id))

pluck我们可以通过使用rails >= 3.2.1 中的方法来简化这一点:

Manufacturer.where(id: Product.uniq.where(category_id: @category.id).
  pluck(:manufacturer_id))

我还想补充一点has_many :manufacturers, :through => :products,由于加入(根据我的经验),大数据上的解决方案可能会慢一些。

于 2012-08-06T09:27:12.743 回答