user2427972
user2427972

Reputation: 75

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.

Upvotes: 3

Views: 4096

Answers (2)

Ryenski
Ryenski

Reputation: 9692

A more efficient way would be to use the distinct and count methods together.

@city_counts = Person.distinct.count(:city)

That way the work is done in the db instead of in Ruby.

Upvotes: 0

David Aldridge
David Aldridge

Reputation: 52336

Just use:

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

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

Upvotes: 8

Related Questions