# Help with activerecord, has\_many and :order, please

**URL:** <https://www.ruby-forum.com/t/help-with-activerecord-has-many-and-order-please/147151>\
**Category:** Rails\
**Created:** [August 28, 2008, 9:13pm UTC](https://www.ruby-forum.com/t/help-with-activerecord-has-many-and-order-please/147151 "2008-08-28T21:13:51Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![olia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/91b2a8/32.png) [@olia](https://www.ruby-forum.com/u/olia)\
**Post date:** [August 28, 2008, 9:13pm UTC](https://www.ruby-forum.com/t/help-with-activerecord-has-many-and-order-please/147151/1 "2008-08-28T21:13:51Z")

</div>

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

Here is what I have:

class Author \< ActiveRecord::Base  
has\_many :books  
end

class Books \< ActiveRecord::Base  
belongs\_to :author  
end

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,  
Olia

---

<div class="post-metadata">

**Author:** ![olia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/91b2a8/32.png) [@olia](https://www.ruby-forum.com/u/olia)\
**Post date:** [August 28, 2008, 10:33pm UTC](https://www.ruby-forum.com/t/help-with-activerecord-has-many-and-order-please/147151/2 "2008-08-28T22:33:03Z")

</div>

You can try sort method with a block:

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

---

<div class="post-metadata">

**Author:** ![olia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/91b2a8/32.png) [@olia](https://www.ruby-forum.com/u/olia)\
**Post date:** [August 28, 2008, 10:51pm UTC](https://www.ruby-forum.com/t/help-with-activerecord-has-many-and-order-please/147151/3 "2008-08-28T22:51:15Z")

</div>

Thanks for the reply!

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

---

<div class="post-metadata">

**Author:** ![olia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/91b2a8/32.png) [@olia](https://www.ruby-forum.com/u/olia)\
**Post date:** [August 29, 2008, 2:37am UTC](https://www.ruby-forum.com/t/help-with-activerecord-has-many-and-order-please/147151/4 "2008-08-29T02:37:09Z")

</div>

Try this:

Book.find(:all, :select =\> “author\_id, count(id) as  
book\_count”, :group =\> “author\_id”, :order =\> “book\_count”)

Regards,  
Jorge.
