group by country with ActiveRecords in Rails
I have a table with users:
name | country |
.. | UK |
.. | US |
.. | US |
.. | UK |
.. | FR |
.. | FR |
.. | UK |
.. | UK |
.. | DE |
.. | DE |
.. | UK |
.. | CA |
.
.
What is the most efficient way with ActiveRecord to get the list of countries in my view and for each country how many users are from, so:
开发者_运维技巧US 123
UK 54
DE 33
.
.
.
Do the following:
counts = Users.count(:group => :country)
Now print the count:
counts.each |country, count| do
p "#{country} - #{count}"
end
# Prints
US 123
UK 54
DE 33
counts["UK"] #-> prints 123
精彩评论