user984621
user984621

Reputation: 48453

How to determine a number of grouped records in Rails?

A table has this structure and data in there:

id | car     | location | ...
-----------------------------
1  | BMW     | US       | ...
2  | Audi    | US       | ...
3  | Audi    | US       | ...
4  | Porsche | CA       | ...
5  | Audi    | US       | ...

I am loading and grouping data in a usual way:

@cars = Cars.where('location = ?', location).group('car')

I'd need to display in a view a number of grouped data - in this case, I would need to print how much of data is in the US for example; so the desired output would be like:

BMW - 1 car
Audi - 3 cars

How to get a number of grouped rows?

Upvotes: 0

Views: 73

Answers (1)

SHS
SHS

Reputation: 7744

Car.where(location: location).group(:car).count #=> e.g. {'BMW' => 1}

Just FYI, you can also group by location AND car.

Car.group(:location, :car).count #=> e.g. {['US', 'BMW'] => 1}

Upvotes: 6

Related Questions