使用activerecord按时间范围有效地查询事务

时间:2013-01-17 17:35:43

标签: ruby-on-rails ruby rails-activerecord

有没有办法让这种方法更有效率?我正在查询大量事务,并且对每个时段执行单独的activerecord查询似乎效率低下。

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

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)

1 个答案:

答案 0 :(得分:2)

首先,您可以使用范围进行更好的查询。我还要将time1time2重命名为startfinish

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

修改

我没有测试过代码,逻辑显示更多