Ruby on Rails:按标签列表过滤所有产品的最佳方式

时间:2013-02-02 23:10:20

标签: sql ruby-on-rails

我有2个型号的产品和标签,具有多对多的关系。

class Product < ActiveRecord::Base
  has_many :product_tags
  has_many :tags, through: :product_tags
end

class Tag < ActiveRecord::Base
  has_many :product_tags
  has_many :products, through: :product_tags
end

和关系模型:

class ProductTag < ActiveRecord::Base
  belongs_to :product
  belongs_to :tag
end

通过给定标签列表搜索产品的最佳方式是什么?产品必须包含所有标签,而不仅仅是其中一个标签。

2 个答案:

答案 0 :(得分:0)

尝试

products = Product.joins(:tags)
tags.each do |tag|
  products = products.where(tags: { name: tag })
end

tags包含您要搜索的代码列表,我假设该代码具有name属性

答案 1 :(得分:0)

我在这里找到了答案https://stackoverflow.com/a/11887362/808175。所以在我的情况下它是:

tags = ['1', '2', '3']
Product.joins(:tags)
       .where(:tags => {:id => tags})
       .group('products.id')
       .having("count(product_tags.tag_id) = #{tags.count}")