2010-08-24 66 views
0

說,如果有一個與領域Ruby on Rails如何處理「按類別從產品組中選擇計數(*)」?

Products 
-------- 
ID 
CategoryID 
Name 
Price 
    ... etc 

表Ruby on Rails的如何能給返回

select count(*) from products group by categoryID 

這是顯示每個類別有多少產品中的表?結果如何,而不是產品對象數組Products.find(:all)

隨着更先進的操作,怎麼樣

select count(*) from products p inner join category c on p.categoryID = c.ID 
    group by categoryID 

select average(price) from products p inner join category c on p.categoryID = c.ID 
    group by categoryID 

回答

7

你可能要檢查出ActiveRecord::Calculations模塊(它確實最什麼你問的,我相信):

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html

一些例子:

計數:

Product.group(:category_id).count 

平均分:

Product.joins(:category).group(:category_id).average(:price) 

這些應該有希望讓你走上正確的道路。但絕對檢查鏈接的文檔,因爲它非常有用。

2

你在問幕幕後發生了什麼,或者結果會是什麼樣子。如果是後者,那麼學會愛控制檯!您可以輕鬆地找到自己:

$ script/console 
Loading development environment (Rails 2.3.8) 

>> Product.count 
=> 229697 

>> Product.count(:group => :category_id) 
=> #<OrderedHash {27=>5588, 33=>41, 28=>156, 34=>22, 23=>15209, 1=>115357, 
    29=>109, 24=>68, 2=>14434, 25=>78576, 31=>85, 26=>4, 32=>48}> 

正如你所看到的,它給你一個有序的哈希映射category_ids的計數的類別。