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!
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!
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")
Find all records which have a count of an association greater than zero - Stack Overflow