ben
ben

Reputation: 6180

rails: accessing a table attribute and using group()

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

Upvotes: 2

Views: 683

Answers (1)

Peter Goldstein
Peter Goldstein

Reputation: 4545

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).

Upvotes: 5

Related Questions