更新时间:2023-11-09 22:24:40
在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.