when doing a ActiveRecord::Base count how do i order by count desc?

耗尽温柔 提交于 2019-12-24 10:25:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!