Search code examples
ruby-on-railsrubysummarization

Doing calculation in ruby on rails Model.sum()


I have a model called Data and some columns called timestamp, value1 and value2. I would like to use it with highstock chart.

Before the chart is printed I would like some calculations on it:

Summarize the result of value1 devided by value2 (value1/value2) by each day or month or year and put it in an array like [[timestamp_day, value1/value2], [...], ...].

I'm able to do the "timestamp-grouping". But I'm hanging on summarize the value1/value2.

Is there a way to do it like .sum(value1/value2)? Or is there any way to define a virtual column that does the calculation?

Thanks & best regards, Andreas


Solution

  • If you're trying to grab the calculated values right from the database you can pass an expression into the active record sum function.

    Data.group(:timestamp).sum("value1 / value2")