Ruby-on-rails 在 Rails 中分组和计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2022334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Group and count in Rails
提问by tladuke
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?
这是用于我的行项目索引视图,它只是一个显示行项目的表格。既然订单项已按设备分组,我该如何在该表中为“计数”创建一列?
回答by Chandra Patni
You can do counton line_itemswhich will return you an ordered hash of device_idand count.
你可以做count的line_items,这将返回你的有序哈希device_id和count。
@project.line_items.group(:device_id).count
回答by Sandip Ransing
hash of devise_id as key and associated records count
devise_id 的哈希作为键和关联的记录计数
@project.line_items.group(:device_id).count
回答by Alex Reisner
Just add a :selectoption:
只需添加一个:select选项:
@line_items = @project.line_items.all(
:group => "device_id",
:select => "device_id, COUNT(*) as count"
)
Then each @line_itemwill have a countattribute.
那么每个人@line_item都会有一个count属性。
回答by bluefoggy
I think you can try this as well.
我想你也可以试试这个。
@project.line_items.group(:device_id).pluck("device_id, count(device_id)")
^^ This gives array of arrays with elements 'device_id and count'
^^ 这给出了元素为“device_id 和 count”的数组数组
回答by rogerdpack
something like
就像是
User.all(:joins => :comments, :select => "users.*, count(comments.id) as comments_count", :group => "users.id")
might also work...
也可能工作...
回答by John Smith
For only count pluckwould be faster here rather than group
因为这里只计数pluck会比group更快
@project.line_items.pluck(:device_id).count
@project.line_items.pluck(:device_id).uniq.count
回答by Psylone
After this commit:
在这次提交之后:
https://github.com/rails/rails/commit/a1c05dd8b9bd3623289d3aa73dda2943d620cc34
https://github.com/rails/rails/commit/a1c05dd8b9bd3623289d3aa73dda2943d620cc34
there's a new way to do the same thing:
有一种新方法可以做同样的事情:
@project.line_items.count(:group => LineItem.arel_table[:device_id])

