tla*_*uke 53 ruby-on-rails count
我知道我以前看过这个,但现在找不到任何东西.我想按特定列对查询进行分组,并能够显示每个组中的查询数量.我得到了第一部分:
@line_items = @project.line_items.all(:group => "device_id")
Run Code Online (Sandbox Code Playgroud)
这是我的订单项索引视图,它只是一个显示订单项的表格.现在,如果订单项按设备分组,如何在该表中创建"计数"列?
Cha*_*tni 108
你可以做count的line_items就是返回device_id和的有序哈希值count.
@project.line_items.group(:device_id).count
Run Code Online (Sandbox Code Playgroud)
San*_*ing 12
devise_id的哈希值作为键和相关记录计数
@project.line_items.group(:device_id).count
Run Code Online (Sandbox Code Playgroud)
我想你也可以试试这个。
@project.line_items.group(:device_id).pluck("device_id, count(device_id)")
Run Code Online (Sandbox Code Playgroud)
^^ 这给出了元素为“device_id 和 count”的数组数组
只需添加一个:select选项:
@line_items = @project.line_items.all(
:group => "device_id",
:select => "device_id, COUNT(*) as count"
)
Run Code Online (Sandbox Code Playgroud)
然后每个@line_item都有一个count属性.