rails:获取标记为x AND y AND z的所有项目

kik*_*ito 8 sql activerecord ruby-on-rails

我有两个型号:ItemTag.两者都有name属性.我想找到标有多个标签的商品.

class Item < ActiveRecord::Base
  has_many :tags
  validates_presence_of :name
end

class Tag < ActiveRecord::Base
  belongs_to :item
  validates_presence_of :name
end
Run Code Online (Sandbox Code Playgroud)

给定一个标签ID列表,我可以很容易地获得用一个标签另一个标签标记的项目列表:

# Find the items tagged with one or more of the tags on tag_ids
Item.all(:conditions => ['tags.id in (?)', tag_ids], :joins => :tags)
Run Code Online (Sandbox Code Playgroud)

如果tag_ids{1,4},那么我将所有图片标记为1或4或两者.

我现在想知道如何获得用-1 4 标记的图片.

我甚至无法想象这里需要的SQL.

ele*_*aut 13

您可以通过对结果进行分组并检查计数来解决此问题:

Item.all(
  :conditions => ['tags.id IN (?)', tag_ids], 
  :joins      => :tags, 
  :group      => 'items.id', 
  :having     => ['COUNT(*) >= ?', tag_ids.length]
)
Run Code Online (Sandbox Code Playgroud)