I have a date(type:DateTime) column and a price(type:Decimal) column within my db. Records are created and saved hourly. I need to create a rake task to go through all of my stored data and create an average price for each day.
Using ActiveRecord, how can I query all of my records, group together all records within each day, create a new average price from those 24 records, and save it as a new record in a different table?
I imagine it would be something like this psuedocode:
Sales.all
loop through them and group records by day
loop through each grouping and create average
average = DailyAverage.create
FYI I have about 10,000 records.
Scope is nice way to select some records and group them. In Sales class define something like
scope :by_date, ->(needful_date) { where{ date == needful_date} }. Then in another model(which relates to another table) define your calculations:It’s just an idea of solution. You’d better understand it and implement yourself.