How to find records, whose has_many through objects include all objects of some list?

谁说胖子不能爱 提交于 2019-12-04 19:42:58

To do this in one query you'd want to take advantage of the common double not exists SQL query, which essentially does find X for all Y.

In your instance, you might do:

class Project < ActiveRecord::Base
  def with_tags(tag_ids)
    where("NOT EXISTS (SELECT * FROM tags
      WHERE NOT EXISTS (SELECT * FROM tagazations
        WHERE tagazations.tag_id = tags.id
        AND tagazations.project_id = projects.id)
      AND tags.id IN (?))", tag_ids)
  end
end

Alternatively, you can use count, group and having, although I suspect the first version is quicker but feel free to benchmark:

def with_tags(tag_ids)
  joins(:tags).select('projects.*, count(tags.id) as tag_count')
    .where(tags: { id: tag_ids }).group('projects.id')
    .having('tag_count = ?', tag_ids.size)
end

This would be one way of doing it, although by no means the most efficient:

class Project < ActiveRecord::Base
   has_many :tagazations
   has_many :tags, :through => :tagazations

   def find_with_all_tags(tag_names)
     # First find the tags and join with their respective projects
     matching_tags = Tag.includes(:projects).where(:name => tag_names)
     # Find the intersection of these lists, using the ruby array intersection operator &
     matching_tags.reduce([]) {|result, tag| result & tag.projects}
   end
end

There may be a couple of typos in there, but you get the idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!