选择带有多个标签的帖子 [英] Selecting posts with multiple tags
问题描述
我正在博客应用中实施标记系统。这个程序有帖子,帖子有很多通过标签标记。或多或少像RailCasts#382 http://railscasts.com/episodes/382-tagging
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?
例如:
Post1具有标签 foo,bar,baz
Post1 has tags "foo, bar, baz"
Post2具有标签 bar,baz
Post2 has tags "bar, baz"
Post3具有标签 bar
Post3 has tags "bar"
如果我搜索[ bar, baz],我的方法将返回帖子1, 2和3。如果我只想返回帖子1和2?
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?
推荐答案
在SQL中,您会执行以下操作: / p>
In SQL, you would do something like
GROUP BY posts.id
HAVING count(tags.name) = 2
在栏杆中表示为
Post.joins(:tags).select('posts.id').where(:tags => { :id => [tag_ids] }
).having("count(tags.name) = ?", tag_ids.count).group('posts.id')
上面的代码假定 tag_ids
是一个ID数组。此外,它仅加载返回的ActiveRecord Post对象集的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.
如果要加载更多字段,请在 select中添加它们
调用,否则删除 select
调用以加载所有帖子字段。只需记住,对于在结果SQL查询中检索到的Post中的每个列/字段,您都需要将该字段添加到 group
调用中。
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.
这篇关于选择带有多个标签的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!