Forum: Ruby on Rails :has_many best practice search order

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Richard S. (Guest)
on 2009-04-16 06:18
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?
Phlip (Guest)
on 2009-04-16 06:38
(Received via mailing list)
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.
This topic is locked and can not be replied to.