# :has\_many best practice search order

**URL:** <https://www.ruby-forum.com/t/has-many-best-practice-search-order/165653>\
**Category:** Rails\
**Created:** [April 16, 2009, 4:18am UTC](https://www.ruby-forum.com/t/has-many-best-practice-search-order/165653 "2009-04-16T04:18:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [April 16, 2009, 4:18am UTC](https://www.ruby-forum.com/t/has-many-best-practice-search-order/165653/1 "2009-04-16T04:18:41Z")

</div>

I have a model\_one that :has\_many model\_two-s, I would like to find the  
ten model\_one’s that have the most model\_two’s. What is the best way to  
do this?

Model\_One.find(:all, :limit =\> 10, :include =\> :model\_two, :order  
=\>“themost of model\_two desc”)

or inorder for me to do this effeciently (I have thousands of  
model\_two-s) would i need to add a column to model\_one, to keep track of  
the number of model\_two-s that model\_one owns. Or is there some index i  
can use? What is the best practice in this situation?

---

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [April 16, 2009, 4:38am UTC](https://www.ruby-forum.com/t/has-many-best-practice-search-order/165653/2 "2009-04-16T04:38:52Z")

</div>

Richard S. wrote:

> I have a model\_one that :has\_many model\_two-s, I would like to find the  
> ten model\_one’s that have the most model\_two’s. What is the best way to  
> do this?

Something like this?

Model\_One.find(:all, :limit =\> 10, :joins =\> :model\_two,  
:order =\> “count(model\_twos.model\_one\_id) desc”,  
:group =\> “model\_ones.id”)

I could do it in raw SQL, but I don’t know the exact match. Fred Cheung  
or  
someone will correct me if I got it wrong!

The :joins is so you don’t eager-load the models and interfere with the  
group  
concept, I suspect. The group is so you are allowed to count within each  
group.
