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

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and 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, count(couriers.first_name) as courier_count
  from service_partners
  left join couriers on =
  group by
  order by courier_count;

Using ActiveRecord it is done by

   :select => ', count(couriers.first_name) as cn ',
   :joins => 'left join couriers on =
   :group => ' ',
   :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?

This topic is locked and can not be replied to.