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.
The following will require the forums to have all the forum tags in the
@tagsarray. I am making the assumption that aforumwill not have the sameforum_tagmore than once.This will produce an SQL query like the following:
This will group all the rows in the join table by forums that match the given tags. If the
COUNTfunction has the value of the total number of tags that you’re looking for (and there are no duplicateforum/forum_tagpairs) then the forum must contain all the tags.To get the leftover tags (question asked in the comments):
Each
Forumobject in@forums_with_leftoverswill have an extra attributeleftover_tagsthat contains a comma separated list of tags in each forum object that is not in the original@tagsvariable.