我喜欢使用chartkick来可视化一些数据。我有一个购买模型,里面有很多购买。
class Purchase < ActiveRecord::Base
attr_accessible :category, :price, :product, :purchase_type
def invert_price
self.price.abs
end
end
标准图表如下所示:
<%= bar_chart Purchase.group(:category).sum(:price) %>
但是我的 :price 记录是负面的。我只需要一个解决方案如何获得倒置价格 (-price) 或价格的绝对值 (price.abs)。
尝试在购买模型中创建一个方法不起作用,因为它无法在 SQL 查询中得到解决。
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
错误:
Mysql2::Error: Unknown column 'invert_price' in 'field list
编写自己的 SQL 查询可以返回正确的结果,但之后 chartkick 是空的。
<%= bar_chart Purchase.select("ABS(SUM(`candystore_purchases`.`price`)) AS sum_price, category AS category").group(:category) %>
任何想法,如何处理?