2010-08-24 68 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的计数的类别。