Ruby on Rails 如何处理“按类别从产品组中选择计数(*)”?
假设有一个包含字段的表,
Products
--------
ID
CategoryID
Name
Price
... etc
Ruby on Rails 如何给出一个返回的表
select count(*) from products group by categoryID
,以显示每个类别中有多少个产品?与 Product 对象数组的 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
怎么样?
Say if there is a table with fields
Products
--------
ID
CategoryID
Name
Price
... etc
How can Ruby on Rails give a table that returns
select count(*) from products group by categoryID
which is to show how many products in each category? How will the result be like, as opposed to Products.find(:all)
which is an array of Product objects?
As a more advanced operation, how about
select count(*) from products p inner join category c on p.categoryID = c.ID
group by categoryID
and
select average(price) from products p inner join category c on p.categoryID = c.ID
group by categoryID
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想查看
ActiveRecord::Calculations
模块(我相信它可以完成您所要求的大部分操作):http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html
一些示例:
计数:
平均:
这些应该有望让您走上正确的道路。不过,一定要查看链接的文档,因为它非常有用。
You might want to check out the
ActiveRecord::Calculations
module (it does most of what you're asking, I believe):http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html
Some examples:
Count:
Average:
Those should hopefully get you on the right path. Definitely check out the linked documentation, though, as it's incredibly useful.
您是在问幕后发生了什么,还是只是想知道结果会是什么样子。如果是后者,那就学会爱上控制台吧!您可以轻松地自己找到答案:
如您所见,它为您提供了一个有序哈希映射category_ids 到这些类别的计数。
Are you asking what is happening behind the scenes or just what will the result look like. If it's the latter, then learn to love the console! You can easily find out for yourself:
As you can see, it gives you an ordered hash mapping category_ids to the counts for those categories.