我想返回所有在Rails控制台中张贴1条以上帖子的Users。
用户has_many :posts
和帖子belongs_to :user
我已经弄乱了where方法,但是找不到任何东西。预先感谢!
答案 0 :(得分:2)
User.joins(:posts).group('users.id').having('count(posts.id) > 1')
joins
方法执行内部联接,该联接导致所有用户与帖子具有联系,而group
方法用于消除所有重复的行。
按user_id
的帖子分组
即
示例-
{
1 => [post_1, post_2, post_3]
2 => [post_5, post_10]
... so on
}
然后应用having
(胜过where
来处理聚合数据)子句having("count(posts.id) > 1")
Find all records which have a count of an association greater than zero - Stack Overflow