Forum: Ruby on Rails Ordering rows by a number of referencing records

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.
Yuri L. (Guest)
on 2007-05-23 12:53
(Received via mailing list)
Hello all,

There are 2 tables in a one-to-many relation. I want to order rows in
the parent
table according to the number of rows in the child table referencing
the parent table.

In SQL I would do it the following way:

select service_partners.id, count(couriers.first_name) as courier_count
  from service_partners
  left join couriers on service_partners.id =
couriers.service_partner_id
  group by service_partners.id
  order by courier_count;

Using ActiveRecord it is done by

ServicePartner.find(:all,
   :select => 'service_partners.id, count(couriers.first_name) as cn ',
   :joins => 'left join couriers on service_partners.id =
couriers.service_partner_id',
   :group => 'service_partners.id ',
   :order => 'cn asc'

You might think why the guy is not using :include => :couriers instead
of :joins.
The answer is that using :include makes ActiveRecord  ignore (and I
can understand why) the :select argument which I need.

So my question is if anybody sees a more elegant way to do this?


Cheers,
Yuri
This topic is locked and can not be replied to.