Search code examples
ruby-on-railsrubypostgresqlactiverecordbigdecimal

Save New Object from Query


I have a rails app with a PostgreSQL database with hourly price data for the last 10 years, and I need to get the daily average price for each day saved in a new DB table. This query groups records by day and returns an average price for each day:

averages = Sale.average(:price, :group => "DATE_TRUNC('day', date)")

The Rails Console response looks like this (a sample of 2 days of data):

{"2013-01-03 00:00:00"=>#<BigDecimal:7fcc7c2e4a28,'0.1752888888 88888889E2',27(27)>, "2013-01-02 00:00:00"=>#<BigDecimal:7fcc7c2e4848,'0.2547086956 52173913E2',27(27)>}

Can anyone suggest how to write some code to save these returned date and averageprice values to a new Object called DailyAverage?


Solution

  • Your response is like:

    {
      'date' => BigDecimal,
      'date2' => BigDecimal,
      'date2' => BigDecimal,
    }
    

    So you can access to each average for each date like this:

    averages = Sale.average(:price, :group => "DATE_TRUNC('day', date)")
    
    averages.each do |date, avg|
      DailyAverage.create(date: date, average: avg.to_f)
    end
    

    This code assumes you have a DailyAverage model with date and average attributes.

    You may have to use a to_date in the each loop:

    averages.each do |date, avg|
      DailyAverage.create(date: date.to_date, average: avg.to_f)
    end