开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜