查找符合所有类别的产品(Rails 3.1)

我正在努力与Rails 3.1.1中的ActiveRecord查询。

我有2个型号,产品和类别,从产品到类别的has_and_belongs_to_many(产品可以有很多类别)。

我正在尝试编写一个搜索查询,该查询将查找具有所有指定类别的产品(想想用户可以选择要搜索的X类别的搜索UI)。

我可以做这个:

results = Product.joins(:category_products).where('category_products.category_id' => [1,5,8]) 

但是返回具有任何这些类别的产品(即产生SQL“IN(1,5,8)”子句)。

如何创建将执行ALL匹配样式的查询? 例如找到包含所有这些category_ids的产品……

您可以使用having子句执行此操作:

 @ids = [1,5,8] query = Product.select('products.id,products.name').joins(:categories) \ .where(:categories => {:id => @ids}) \ .group('products.id, products.name') \ .having("count(category_products.category_id) = #{@ids.length}") 
 results = Product.joins(:category_products) [1,5,8].each do |category| results = results.where('category_products.category_id' => category) end