2010-11-17 54 views
1

一個例子是...當做一個ActiveRecord :: Base計數如何命令計數desc?

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

返回正確的結果,但不是在orderedhash對象的實際計數恢復。

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

返回計數但未按降序排序......我該怎麼做?

我想我寧願使用.find ..但我會採取.count,如果我可以排序它。

+0

我認爲使用find來獲取計數的問題是聚合/計算列不會以colum/field的形式出現在對象上。 (我可能說錯了) – Kirby 2010-11-17 19:41:52

回答

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

這將返回一個Pet對象數組,並且對於所看到的計數沒有值。 – Kirby 2010-11-17 19:39:08

+0

你可以用array.first.count和array.first.pet_type來訪問它 – 2010-11-17 19:41:14

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

問題是我沒有訪問計數值... – Kirby 2010-11-17 18:49:37

+0

它返回pet_types w/o計數的有序散列。 – Kirby 2010-11-17 18:50:02

0

這正常工作與MySQL,但如果切換數據塊可能不轉移阱:

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

沒有去sqlite3下的我。他們仍然沒有秩序。我可以在事實之後返回的對象上進行操作..但我希望find/count方法中有一些東西。 – Kirby 2010-11-17 19:36:17

+0

什麼版本的導軌?我只注意到rails 3從count方法返回一個OrderedHash。我也只是試圖用rails 3和sqlite數據庫,它對我來說工作得很好。 – 2010-11-17 20:24:29

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

注意:這將返回的記錄,而不是一個ActiveRecord的數組:關係。注意2:使用大小,不計數,因爲count會執行對數據庫的sql調用。