Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用activerecord按时间范围高效查询事务_Ruby On Rails_Ruby_Rails Activerecord - Fatal编程技术网

Ruby on rails 使用activerecord按时间范围高效查询事务

Ruby on rails 使用activerecord按时间范围高效查询事务,ruby-on-rails,ruby,rails-activerecord,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(toda

有没有办法使这种方法更有效?我正在查询大量事务,对每个期间执行单独的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)
def self.transactions(期间)
今天
time1=Time.utc(今天.年,今天.月,今天.日,9,30,0)
time2=Time.utc(今天.年,今天.月,今天.日,16,0,0)
交易记录按时段={}
而time1transactions=self.where(“创建时间>=”和创建时间首先,您可以使用范围进行更好的查询。我还将
time1
time2
重命名为
start
finish

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
transactions.reduce(Hash.new{h,k{h[k]=[])do |句点,事务|
#计算此事务经过了多少个期间
偏移量=(transaction.created\u at-start)。到\u i/期间
#找出实际的周期
事务处理周期=开始+抵销*周期

期间[交易期间]我说,在数据库中完成所有操作:启动一个查询并返回已分组的数据。这就是数据库的用途,处理数据。我将不得不对reduce进行一些实验,以了解它。感谢您的回答。是的,我知道了这一点,并打算在这里发表评论,但不确定如何使用它。很好的解决方案,它缩短了工作时间为该功能标记时间,特别是在查询短时间段时。再次感谢。