Question

Chartkick is amazing, and I can do super simple things like

<%= column_chart Device.joins(:reviews).group(:brand).average(:average_rating) %>

and get results like:

enter image description here

Now, the problem is that the labels aren't fed through to chartkick. This is what chartkick uses to render the chart:

Chartkick.ColumnChart("chart-5", {"#<Brand:0x00000008a3c048>":"78.8","#<Brand:0x0000000879e840>":"80.70000712076823","#<Brand:0x0000000853e9d8>":"81.11111111111111","#<Brand:0x000000082808e0>":"73.42857142857143"}, {});

So, the big question is... How can I use this super easy querying method but get the brand names on the chart?

I tried:

<%= column_chart Device.joins(:reviews).group(:'brand.name').average(:average_rating) %>

...and other variations to no avail...

Was it helpful?

Solution

Basically I just needed to make a small change to my query:

<%= column_chart Device.joins(:reviews).includes(:brand).group(:'brands.name').average(:average_rating) %>

Then I ended up re-ordering this by average ratings instead of brand name:

devices = Device.joins(:reviews).includes(:brand).group('brands.name').average(:average_rating)
arr = styles.to_a
arr.map! { |pair| [pair.first, pair.second.to_f] }
arr.sort! { |a, b| a.second <=> b.second }
@sorted_hash = ActiveSupport::OrderedHash[arr]

View:

<%= column_chart @sorted_hash %>

Bingo:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top