TopperH
TopperH

Reputation: 2223

Selecting posts with multiple tags

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?

Upvotes: 2

Views: 1031

Answers (1)

kits
kits

Reputation: 476

In SQL, you would do something like

GROUP BY posts.id
HAVING count(tags.name) = 2

In rails it translates to

Post.joins(:tags).select('posts.id').where(:tags => { :id => [tag_ids] }
).having("count(tags.name) = ?", tag_ids.count).group('posts.id')

The above code assumes that tag_ids is 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 select call, or otherwise remove the select call 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 the group call.

Upvotes: 3

Related Questions