Find Products matching ALL Categories (Rails 3.1)

后端 未结 2 953
情书的邮戳
情书的邮戳 2021-01-03 17:01

I am struggling with an ActiveRecord query in Rails 3.1.1.

I have 2 models, Product and Category, with a has_and_belongs_to_many from Product to Category (a Product

相关标签:
2条回答
  • 2021-01-03 17:22
    results = Product.joins(:category_products)
    [1,5,8].each do |category|
      results = results.where('category_products.category_id' => category)
    end
    
    0 讨论(0)
  • 2021-01-03 17:41

    You can do this with a having clause:

    @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}")
    
    0 讨论(0)
提交回复
热议问题