I like to use chartkick to visualize some data. I have a Purchase model with many purchases in it.
class Purchase < ActiveRecord::Base
attr_accessible :category, :price, :product, :purchase_type
def invert_price
self.price.abs
end
end
A standard chart would look like:
<%= bar_chart Purchase.group(:category).sum(:price) %>
But my :price records are negativ. I just need a solution how I get to a inverted price (-price) or the absolute value of price (price.abs).
Trying to create a method in the Purchase model doesn't work, because it can't get resolved in a SQL query.
class Purchase < ActiveRecord::Base
attr_accessible :category, :price, :product, :purchase_type
def invert_price
self.price.abs
end
def invert_price
self.price.abs
end
end
Error:
Mysql2::Error: Unknown column 'invert_price' in 'field list
Writing a own SQL query could give back the right result, but chartkick was empty after it.
<%= bar_chart Purchase.select("ABS(SUM(`candystore_purchases`.`price`)) AS sum_price, category AS category").group(:category) %>
Any ideas, how to handle this?