views:

148

answers:

2

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?

A: 

Just add a :select option:

@line_items = @project.line_items.all(
  :group  => "device_id",
  :select => "device_id, COUNT(*) as count"
)

Then each @line_item will have a count attribute.

Alex Reisner
hrm, I put debug(@line_items) in my view, but I don't see any counts, so I don't think I'm understanding you. I think the output is exactly the same as without the select option.
tladuke
this actually works, but not if you have an :include
tladuke
The debug method won't show the count because it's not an ActiveRecord attribute, but there *is* a count attribute on each object. In any case, Chandra's solution is much better.
Alex Reisner
+2  A: 

You can do count on line_items which will return you an ordered hash of device_id and count.

@project.line_items.count(:group => "device_id")
Chandra Patni