0

多対多の関係を持つ 2 つのモデル Product と Tag があります。

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

指定されたタグのリストで製品を検索する最適な方法は何ですか? 製品には、タグの 1 つだけでなく、すべてのタグが必要です。

4

2 に答える 2

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}")
于 2013-02-09T01:51:48.957 に答える
0

試す

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

tags検索するタグのリストが含まれており、タグにはname属性があると想定しています

于 2013-02-03T00:15:20.873 に答える