Is there a way to make this method more efficient? I am querying a large number of transactions and it seems inefficient to perform a separate activerecord query for each period.
Should I make a single query for the whole day and sort through the results, grouping them by period? If so, what’s the most efficient way to do this? Look forward to your thoughts.
def self.transactions(period)
today = Date.today
time1 = Time.utc(today.year, today.month, today.day, 9, 30, 0)
time2 = Time.utc(today.year, today.month, today.day, 16, 0, 0)
transactions_by_period = {}
while time1 < time2
transactions = self.where("created_at >= ? and created_at <= ?", time1, time2)
transactions_by_period[time1] = transactions
time1 += period
end
return transactions_by_period
end
#todays_transactions_by_hour = Stock.transactions(1.hour)
First off, you can use ranges for nicer queries. I’d also rename
time1andtime2tostartandfinishThen you can reduce this to get them by periods.
Edit
I haven’t tested the code, it is shown more for the logic