I’m building an app where each :referral has_many :sales.
In a list of all referrals, I’m displaying referral.date,
referral.other_details, and also referral.sales.count. I want to able
to sort this list by that last column – the number of sales per
Abstractly, I want to do something like
@referrals=Referral.find(:all, :order=>sales.count_all). But nothing
like this works, because when this initial SQL statement is executed,
the total sales per referral haven’t yet been calculated. They get
calculated afterwards, in n separate queries.
How to proceed? @referrals=Referral.find(:all, :include=>:sales)
doesn’t really help. That would allow me to order by a column in the
sales table, but it doesn’t get me any closer to being able to sort by
the aggregated number of sales per referral.
Any thoughts on how to do this? I think I can write the SQL to do it
manually - but can it be accomplished without dropping to find_by_sql?