查找具有所有关联ID的对象的查询(Rails 4)

时间:2014-01-31 09:58:26

标签: sql ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-4

背景:帖子通过CommunityPosts拥有许多社区。我理解以下查询返回与这些community_ids中的任何一个相关联的帖子。

Post.joins(:communities).where(communities: { id: [1,2,3] })

目标:我想查询与数组中所有三个community_ids相关联的帖子。将社区1,2和3作为关联的帖子

编辑:请假设数组的长度未知。使用此数组进行说明。

2 个答案:

答案 0 :(得分:1)

试试这个,

ids=[...]
Post.joins(:communities).select(“count(communities.id) AS cnt”).where(id: ids).group(‘post.id’).having(cnt: ids.size)

答案 1 :(得分:1)

ids = [1, 2, 3] # and etc
Post.joins(:communities).where("communities.id IN ?", ids)
希望它有所帮助。