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?
Your response is like:
So you can access to each average for each date like this:
This code assumes you have a
DailyAveragemodel withdateandaverageattributes.You may have to use a
to_datein the each loop: