Photo-1 Photo-2 Photo-3 Photo-4 Photo-5 Photo-6

@brentmc79

@brentmc79

Full-time web developer. Part-time smart ass.

I'm Brent Collier.

After a year and a half as an engineer on Twitter's Trust & Safety team, I'm looking for my next gig. Contact me if you know of something interesting.

#

Order by Associated Model Count

Posted on 04/26/2011

Say you've got an Author model, and that model has_many :books. Here's how to retrieve the list of models, order by the number of books they've each authored:

Author.joins(:books).select("authors.*, count(books.id) as books_count").order("books_count DESC").group("authors.id")

Note that if you don't include the group condition that it return an Author record for each book. So if an author has written four books, then that author will appear four times in the resulting array.