-3

I want to return all of the Users with more than 1 post in rails console.

A User has_many :posts and a Post belongs_to :user

I have messed around with the where method but I couldn't find anything. Thanks in advance!

Steez
  • 219
  • 5
  • 17
  • Have you tried `User.joins(:posts).where(posts: Post.all)`? – jvillian Apr 11 '19 at 19:08
  • Possible duplicate of [Find all objects that have greater than x of a certain association](https://stackoverflow.com/questions/29665494/find-all-objects-that-have-greater-than-x-of-a-certain-association) – Yurii Verbytskyi Apr 11 '19 at 21:41

1 Answers1

5
User.joins(:posts).group('users.id').having('count(posts.id) > 1')

The joins method performs an inner join which results in all the users with a relationship to posts, and the group method is used to eliminate all duplicate rows.

Group by posts with user_id i.e example -

{
  1 => [post_1, post_2, post_3]
  2 => [post_5, post_10]
  ... so on
}

then apply having (prefered over where to work on aggregated data) clause having("count(posts.id) > 1")

Having vs Where

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

Anand
  • 6,457
  • 3
  • 12
  • 26
  • 2
    Hi! While this may be a solution to the question, code only answers are generally discouraged on SO. Please take some time to edit your response with an explanation as to why this is a solution as it will help OP and future visitors of the site. – d_kennetz Apr 11 '19 at 19:23