Help with activerecord, has_many and :order, please

very much a newbie, so please excuse the basic question.

Here is what I have:

class Author < ActiveRecord::Base
has_many :books

class Books < ActiveRecord::Base
belongs_to :author

What I am trying to do is find all Authors and list them in the order
of how many books they have. It seems that this should be pretty
straight-forward, but it’s hard to google for…

Any help greatly apprciated!

thank you,

You can try sort method with a block:

Author.find(:all).sort {|x,y| x.books.size <=> y.books.size}

Thanks for the reply!

Unfortunately, I need a way to do it in a query, because I need it to
be part of pagination.

Try this:

Book.find(:all, :select => “author_id, count(id) as
book_count”, :group => “author_id”, :order => “book_count”)


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs