1

Say I have a Users table, and each user has a country_id (the list of countries is stored in another table).

I want to display a list of each country and how many members it has, ie:

Canada: 16
Romania: 12
USA: 9

I was using some raw SQL, but the move to postgres was messy, so I'd like to use a cleaner implementation. Is there a nice 'railsy' way to go about getting said list?

3
  • please share what you have tried,along with the table schema
    – Cris
    Jan 15, 2014 at 11:38
  • ActiveRecord methods group and count should be all you need here. Jan 15, 2014 at 11:40
  • What I have is fairly involved (and probably overly complex), so I'd like to just go from the ground floor here. I'm sure this is a relatively common type of query, so I'd like any and all advice! You can imagine the table schema is just a User table with an ID, name and country_id column, and a Country table with an id and name.
    – opticon
    Jan 15, 2014 at 11:41

3 Answers 3

5

This should return a hash with country_id => count pairs:

@users_by_country = User.group(:country_id).count
#=> { 1 => 104, 2 => 63, ... }

The generated SQL query looks like this:

SELECT COUNT(*) AS count_all, country_id AS country_id FROM `users` GROUP BY country_id

And in your view:

<% @countries.each do |country| %>
  <%= country.name %>: <%= @users_by_country[country.id] %>
<% end>
2

though you have not provided any detail . so its hard to answer exaclty, but may be this will help

User.group(:country_id).count
1
  • 1
    Definitely it. @Stefan beat you by a minute, so I've gotta give him the check, but you get an upvote and my eternal gratitude!
    – opticon
    Jan 15, 2014 at 11:44
0

If you have a Countries model and you want to do it a little differently so that it is more human readable you could use .map.

Countries.map{|o| { Country: o.name, members: o.members.count } }

Obviously you need to have the associations. If countries is just a field on User then this will not work.

BR

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.