在进行ActiveRecord :: Base计数时如何按计数desc进行排序?

时间:2010-11-17 18:38:58

标签: ruby-on-rails activerecord

一个例子是......

Pets.find(:all, :select => 'count(*) count, pet_type', :group => 'pet_type', :order => 'count')

返回正确的结果,但不返回返回的orderedhash对象中的实际计数。

Pets.count(:all, :group => 'pet_type')

返回计数但不按降序排序......我该怎么做?

我想我更喜欢使用.find ..但如果可以对它进行排序,我会接受.count。

4 个答案:

答案 0 :(得分:3)

Pets.find(:all, :select => '*, count(*) AS count, pet_type', :group => 'pet_type', :order => 'count')

答案 1 :(得分:0)

Pets.find(:all, :select => 'count(*) count, pet_type', :group => 'pet_type', :order => 'count DESC')

答案 2 :(得分:0)

这适用于MySQL,但如果切换DB可能无法很好地传输:

Pets.count(:all, :group => 'pet_type', :order => 'count(*) DESC')

答案 3 :(得分:0)

@pets=Pets.include(:meals_per_days).sort do |a,b| 
  a.meals_per_days.size <=> b.meals_per_days.size
end

注意:这将返回一个记录数组,而不是ActiveRecord:Relation。

注意2:使用size而不是count,因为count将执行对db的sql调用。