Alex Rivera | Logout

Group and count in Rails

Asked 2010-01-07T17:43:13.863
88

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?

Edit
Report

1 Answer

164

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
answered 2010-01-07T17:57:08.390

Your Answer