1

背景:帖子通过CommunityPosts有许多社区。我了解以下查询返回与这些community_id中的任何一个关联的帖子。使用所有关联ID查找对象的查询(Rails 4)

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

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

编辑:请假定数组的长度未知。用于解释目的这个数组。

回答

1

试试这个,

ids=[...] 
Post.joins(:communities).select(“count(communities.id) AS cnt”).where(id: ids).group(‘post.id’).having(cnt: ids.size) 
1
ids = [1, 2, 3] # and etc 
Post.joins(:communities).where("communities.id IN ?", ids) 

希望它帮助。