问题
an example would be...
Pets.find(:all, :select => 'count(*) count, pet_type', :group => 'pet_type', :order => 'count')
returns the correct results but not the actual counts in the orderedhash object returned.
Pets.count(:all, :group => 'pet_type')
returns the count but are not sorting in a descending fashion... how would i do this?
I think i'd prefer to use .find .. but i'll take .count if i can sort it.
回答1:
Pets.find(:all, :select => '*, count(*) AS count, pet_type', :group => 'pet_type', :order => 'count')
回答2:
Pets.find(:all, :select => 'count(*) count, pet_type', :group => 'pet_type', :order => 'count DESC')
回答3:
This works fine with MySQL but might not transfer well if you switch DBs:
Pets.count(:all, :group => 'pet_type', :order => 'count(*) DESC')
回答4:
@pets=Pets.include(:meals_per_days).sort do |a,b|
a.meals_per_days.size <=> b.meals_per_days.size
end
Note : This will returns an array of records, not an ActiveRecord:Relation.
Note2 : Use size, not count, as count will execute sql calls to the db.
来源:https://stackoverflow.com/questions/4207889/when-doing-a-activerecordbase-count-how-do-i-order-by-count-desc