在Rails中进行分组和计数 [英] Group and count in Rails
本文介绍了在Rails中进行分组和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我以前见过,但现在找不到任何东西。我想按某个列对查询进行分组,并能够显示每个组中有多少个查询。我把第一部分记下来:
I know I've seen this before but I can't find anything now. I want to group a query by a certain column and be able to display how many are in each group. I got the first part down:
@line_items = @project.line_items.all(:group => "device_id")
这是我的订单项索引视图,它只是一个显示订单项的表格。既然订单项已按设备分组,如何在该表中为计数创建一列?
This is for my line item index view, which is just a table displaying the line items. How do I make a column in that table for "count" now that the line items are grouped by device?
推荐答案
您可以在 line_items
上执行 count
,这将返回 device_id $ c $的有序哈希c>和
count
。
You can do count
on line_items
which will return you an ordered hash of device_id
and count
.
@project.line_items.group(:device_id).count
这篇关于在Rails中进行分组和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文