Reputation: 3337
I'm using the latest Chartkick 2.2.5 and Rails 5.1.4 and I'm trying to graph out Units (vehicles) and their statuses (Available/unavailable/etc) and get a count and a graph via chart kick.
Here is what my view code looks like:
<%= column_chart Status.includes(:units).order("name asc").map {|s| {name: s.name, data: s.units.group_by{|u| u.name}.count}}, library: {backgroundColor: "#F8F8F8"} %>
This results in the following display:
So it's iterating over the statuses but is not displaying the unit count for each status. Perhaps my ruby is wrong or perhaps group_by is not what I'm looking for. But I was hoping for some help with this.
I have groupdate installed and am graphing other objects by day/week/month no problem, however this particular graph needs a raw count of each unit by status and I'm not exactly sure which way to approach this. I will continue to google and refer to the Ruby API docs but in the meantime any help is appreciated.
Update
I made some progress with this, however the Statuses if assigned to more than one unit (in this example "Out of Service" is assigned to two units) then the units show up twice as you can see in the picture. Here is my updated code:
<%= column_chart Status.joins(:units).order("name asc").map {|s| {name: s.name, data: s.units.group('units.name').count}}, library: {backgroundColor: "#F8F8F8"} %>
Here is the result:
So there's somewhere in my ruby where I'm unable to make the results distinct or unique. I've tried calling uniq
on both status and units and it errors out with undefined method for Class and suggests group_by
as an alternative instead of group.
If I change one of the units to a different status that is not in use by any other unit the chart displays properly so I'm thinking my Ruby is janky and needs a bit of assistance.
Upvotes: 1
Views: 746
Reputation: 3337
I'm still working on the ordering of the statuses and units, but I was able to get distinct results by adding .uniq in the method chain like so:
Status.joins(:units).uniq.map {|s| {name: s.name, data: s.units.group(:name).count}}
Upvotes: 1