I’m implementing a tagging system on a blog app. This app has posts, posts have many tags through taggings. More or less like RailCasts #382 http://railscasts.com/episodes/382-tagging
I will use checkboxes to select posts with multiple tags like this:
Post.joins(:tags).where(:tags => { :id => [tag_ids] } )
But what if I want to join posts that have all the required tags instead of posts that meet only one requirements?
For exapmle:
Post1 has tags “foo, bar, baz”
Post2 has tags “bar, baz”
Post3 has tags “bar”
If I search for [“bar”, “baz”] my method returns posts 1, 2 and 3. What If I want to return only post 1 and 2?
In SQL, you would do something like
In rails it translates to
The above code assumes that
tag_idsis an array of ids. Also, it only loads the ids for the returned set of ActiveRecord Post objects.If you want to load more fields, add them in the
selectcall, or otherwise remove theselectcall to load all Post fields. Just remember that for every column/field from Post that is retrieved in the resulting SQL query, you will need to add that field to thegroupcall.