Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group and count in 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?

like image 467
tladuke Avatar asked Jan 07 '10 17:01

tladuke


People also ask

How does count work with group by?

SQL COUNT( ) with group by and order byThe GROUP BY makes the result set in summary rows by the value of one or more columns. Each same value on the specific column will be treated as an individual group.

WHAT IS group in Ruby?

The group_by() of enumerable is an inbuilt method in Ruby returns an hash where the groups are collectively kept as the result of the block after grouping them. In case no block is given, then an enumerator is returned.

What is Active Record in Ruby?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

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 
like image 100
Chandra Patni Avatar answered Oct 15 '22 01:10

Chandra Patni