I have a number of associated models:
Company has_many :clients (which belongs_to :company)
Client has_many :groups (which belongs_to :client)
Group has_many :orders (which belongs_to :group, :counter_cache => true)
Now, I need to find all companies and sort them by their orders, highest to lowest. Since I have the groups orders_count column, I am pretty sure I can just order by groups.orders_count. Then I need to iterate over the companies, showing the total orders placed alongside.
I've been trying to come up with a find for this. I have a MySQL database, if it comes down to a find_by_sql or something.
companies = Company.find(
:all,
:include => { :clients => :groups },
:select => "companies.*, groups.orders_count",
:group => "companies.id",
:order => "groups.orders_count"
)
Any help or push in the right direction appreciated! Thanks.