AnApprentice
AnApprentice

Reputation: 111000

How to query based on a associated model condition?

I have the following:

Groups: id, title
GroupMembers: id, group_id, name

Groups have many group_members

How can I query the db to get all Groups which have at least 2 GroupMembers?

Thanks

Upvotes: 0

Views: 23

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

Try this:

Group.joins("(
  SELECT group_id 
  FROM group_members
  GROUP BY group_id
  HAVING COUNT(1) > 1
 ) a ON a.member_id = groups.id")

Upvotes: 1

Related Questions