Search code examples
ruby-on-railsactiverecord

Rails round Active Record query result


Simple question I cannot seem to figure out:

In a controller:

@clientsMonthYearQuery = Client.group(:month_year)

In a view I have this query

@clientsMonthYearQuery.average(:charge)

How would I round the query result to round the average to 2 decimal spots?

*note there is a business reason for chaining the AR calc in the view, the example I gave is simplified from the real thing


Solution

  • I just came across this while trying to do the same thing with chartkick. I convert the results to an array (an array of arrays actually where each sub-array is [client,charge]) and then round the second value in each sub-array, like so:

    @clientsMonthYearQuery.average(:charge).to_a
    @clientsMonthYearQuery.each do |record|
      record[1] = record[1].round(2)
    end
    

    I do this in the controller however. You could certainly keep the results as a hash and iterate over it similarly, but I prefer arrays (and chartkick accepts both) and this works for me.