Query Activerecord HABTM relationship to include ALL elements of an array

时光毁灭记忆、已成空白 提交于 2019-12-24 06:25:12

问题


I have a Forum and ForumTag HABTM relationship. I also have an array of variables named @tags . This array contains the names of some ForumTags. I want to be able to query and find all forums that have ALL the values of the array. I currently have:

@forums = Forum.joines(:forum_tags).where(:forum_tags => {:name => @tags}).includes(:forum_tags).all

However, this returns all the forums that have AT LEAST ONE value in the array.


回答1:


The following will require the forums to have all the forum tags in the @tags array. I am making the assumption that a forum will not have the same forum_tag more than once.

@forums = Forum.joins(:forum_tags).where(:forum_tags => {:name => @tags}).group("forums.id").having(['COUNT(*) = ?', @tags.length]).includes(:forum_tags).all

This will produce an SQL query like the following:

@tags = ['foo', 'bar']

SELECT forums.id, forum_tags.id FROM forums
  LEFT OUTER JOIN forum_tags_forums on forum_tags_forums.forum_id = forums.id
  LEFT OUTER JOIN forum_tags ON forum_tags.id = forum_tags_forums.forum_tag_id
  WHERE forum_tags.name IN ('foo', 'bar')
  GROUP BY forums.id
  HAVING COUNT(*) = 2;

This will group all the rows in the join table by forums that match the given tags. If the COUNT function has the value of the total number of tags that you're looking for (and there are no duplicate forum/forum_tag pairs) then the forum must contain all the tags.

To get the leftover tags (question asked in the comments):

forum_tags = ForumTag.where(:name => @tags)

@forums_with_leftovers = Forum.select("forums.*, GROUP_CONCAT(forum_tags.name) AS leftover_tags").joins(:forum_tags).where(['forums.id IN (?) AND NOT forum_tags.id IN (?)', @forums, forum_tags]).group("forums.id").all

Each Forum object in @forums_with_leftovers will have an extra attribute leftover_tags that contains a comma separated list of tags in each forum object that is not in the original @tags variable.



来源:https://stackoverflow.com/questions/9448827/query-activerecord-habtm-relationship-to-include-all-elements-of-an-array

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