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

时间:2012-08-09 14:42:00

标签: ruby-on-rails ruby activerecord

我正在使用Rails 3.1.1中的ActiveRecord查询。

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

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

我可以这样做:

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

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

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

2 个答案:

答案 0 :(得分:4)

您可以使用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}")

答案 1 :(得分:0)

results = Product.joins(:category_products)
[1,5,8].each do |category|
  results = results.where('category_products.category_id' => category)
end
相关问题