Ruby on Rails如何处理"按类别从产品组中选择计数(*)"?

nop*_*ole 0 mysql aggregate ruby-on-rails

假设有一个包含字段的表

Products
--------
ID
CategoryID
Name
Price
  ... etc
Run Code Online (Sandbox Code Playgroud)

Ruby on Rails如何提供返回的表

select count(*) from products group by categoryID
Run Code Online (Sandbox Code Playgroud)

这是为了显示每个类别中有多少产品?结果如何,而不是Products.find(:all)Product对象的数组?

作为一个更先进的操作,怎么样

select count(*) from products p inner join category c on p.categoryID = c.ID 
  group by categoryID
Run Code Online (Sandbox Code Playgroud)

select average(price) from products p inner join category c on p.categoryID = c.ID 
  group by categoryID
Run Code Online (Sandbox Code Playgroud)

jer*_*ith 7

您可能想要查看该ActiveRecord::Calculations模块(我相信,它完成了您要求的大部分内容):

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

一些例子:

计数:

Product.group(:category_id).count
Run Code Online (Sandbox Code Playgroud)

平均:

Product.joins(:category).group(:category_id).average(:price)
Run Code Online (Sandbox Code Playgroud)

那些应该有希望让你走上正确的道路.但是,请查看链接的文档,因为它非常有用.