0

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?

zishe
  • 10,665
  • 12
  • 64
  • 103
neonmate
  • 509
  • 4
  • 10

1 Answers1

2

Try:

<%= bar_chart Purchase.group(:category).sum("ABS(price)") %>
Andrew Kane
  • 3,200
  • 19
  • 40
  • `SELECT SUM(ABS(price)) AS sum_abs_price, category AS category FROM 'purchases' GROUP BY category` is the produced sql query, exactly what I was searching for. Thanks a lot! – neonmate Jun 23 '14 at 13:10