Selecting posts with multiple tags

自闭症网瘾萝莉.ら 提交于 2019-12-09 21:23:20

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12569873/selecting-posts-with-multiple-tags

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