如何在Rails控制台中找到所有帖子数超过1的用户

时间:2019-04-11 18:52:18

标签: ruby-on-rails ruby activerecord

我想返回所有在Rails控制台中张贴1条以上帖子的Users。

用户has_many :posts和帖子belongs_to :user

我已经弄乱了where方法,但是找不到任何东西。预先感谢!

1 个答案:

答案 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")

Having vs Where

Find all records which have a count of an association greater than zero - Stack Overflow