Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - count records by value

I am trying to group records based on a value from a column, so I can use it to display the information elsewhere. At the moment I have this working if I specify the values in the column -

@city_count = People.select('city,count(*)').where("city in ('london', 'paris')").group(:city).count

This works fine if I want a list of people in London and Paris but if the city list also has Sydney, New York, Rio etc I don't want to keep adding the extra cities to the 'city in', I would like this to just find the people selected by each city.

Does anyone know the best way of doing this? Also if it can include NULL values as well.

like image 573
user2427972 Avatar asked Sep 03 '25 16:09

user2427972


1 Answers

Just use:

@city_count = People.group(:city).count

to get counts for all cities. This will include an entry for nil.

like image 130
David Aldridge Avatar answered Sep 05 '25 11:09

David Aldridge