1

有没有办法让这种方法更有效?我正在查询大量事务,并且为每个期间执行单独的活动记录查询似乎效率低下。

我应该对一整天进行一次查询并对结果进行排序,按时间段分组吗?如果是这样,最有效的方法是什么?期待你的想法。

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)
4

1 回答 1

2

首先,您可以使用范围进行更好的查询。我也会重命名time1time2startfinish

transactions = self.where(:created_at => start..finish)

然后你可以减少它以按周期获取它们。

transactions.reduce(Hash.new{|h, k| h[k] = []) do |periods, transaction|
  # Calculate how many periods have gone by for this transaction
  offset = (transaction.created_at - start).to_i / period
  # Find the actual period
  transaction_period = start + offset * period
  periods[transaction_period] << transaction
  periods
end

编辑

我还没有测试代码,它显示了更多的逻辑

于 2013-01-17T18:03:23.987 回答