2

I am trying to access a attribute from a table named cities from the User model. the two table are associated. I want to make a pie-chart of the user cities, am using chartkick (you can check it out I have given the link)

in my view I have:

<%= pie_chart User.city.group("name").count %>

someone advise me, since it is not working.


update:

<%= pie_chart User.group("city_id").count %>, it is able to group the number of users per city but the label is city id

I want to improve the chart to have the label of the city names

ben
  • 6,000
  • 5
  • 35
  • 42

1 Answers1

5

From your question I'm not entirely sure what you're trying to do, but it sounds like you're trying to chart the number of users per city - is that right? If so, you can get the statistics by doing something like

User.group('city_id').count

That will result in a has that has the users per city, but the label will be the city id, not the name. We can improve this by adding a join clause and grouping by the name:

User.joins(:city).group('cities.name').count

I think, based on your question, that this will give you what you want. (I've made a couple of assumptions about the column and table names here - city_id, cities).

Peter Goldstein
  • 4,479
  • 2
  • 19
  • 17
  • yes you are right, I want to group by the cities name. but it is giving this error undefined method `join' for #, – ben Nov 05 '13 at 18:53
  • Sorry, typo in my answer. Should be 'joins' not 'join'. Try that. – Peter Goldstein Nov 05 '13 at 19:00
  • thanks man for the fast reply,it worked. so if I may ask, why was this statement not working? <%= pie_chart User.city.group("name").count %> – ben Nov 05 '13 at 19:26
  • Because User.city yields a query that looks something like `["SELECT cities.* WHERE id = ?", user.id]` - it looks up a particular city. What you want is a query against users, and you want to group by the city. That's what the first query in my answer does. To add the city names, you need to join against the cities table and use the name rather than the cities id. The underlying SQL in this case looks something like `SELECT cities.name, count(*) from users join on (users.city_id = cities.id) group by cities.name` – Peter Goldstein Nov 05 '13 at 19:33
  • What's the other question? Have you posted it? – Peter Goldstein Nov 05 '13 at 19:50
  • http://stackoverflow.com/questions/19797869/making-a-pie-chart-of-the-user-age-in-rails – ben Nov 05 '13 at 20:04