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

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

尝试

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

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

我 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}")

最新更新