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.