2

Using rails 4 and postgres 9.1, how do I write a query to find the parent record (or records in the event of a tie) which have the most children given a standard has_many :through relationship (parents have many children and children belong to a parent).

l85m
  • 808
  • 1
  • 10
  • 19
  • 2
    possible duplicate of [Rails 3 ActiveRecord: order by count on association](http://stackoverflow.com/questions/8696005/rails-3-activerecord-order-by-count-on-association) – infused Aug 13 '14 at 22:38
  • Thanks @infused - the link helped. I searched for about 20 minutes for max associations and synonyms, but didn't think to look for ordering by count. Will leave this up incase someone else uses the same terms as me. – l85m Aug 13 '14 at 22:53

1 Answers1

2

This works:

Parent.select('parents.id, COUNT(children.id) AS children_count').joins(:children).group('parents.id').order('children_count DESC').take(1).first

infused's link provides a few alternatives.

l85m
  • 808
  • 1
  • 10
  • 19