【问题标题】:N+1 query issuesN+1 查询问题
【发布时间】:2016-07-30 01:43:52
【问题描述】:

我有 2 个模型 UserOrder。我需要生成一个图表,它将在数组中检索每月余额。在我的Order 表中,我有earningscosts。以下是我提出的一些建议:

用户.rb

class User < ActiveRecord::Base

def baltime(time) #This will return balance based on time
  orders.where("created_at < ?", time).map(&:earning).compact.inject(:+).to_f -
  orders.live.where("created_at < ?", time).map(&:costs).compact.inject(:+).to_f
end

def group_by_months
  result = []
  forteenmonths = 14.times.map { |i| (Date.today - (i).month)}.reverse
  forteenmonths.each do |d|
    result << self.baltime(d)
  end
  result #This will return an array of the order balances
end

上面的方法是有效的,但是,它会从数据库中调用 14 个查询。有没有更好的方法可以解决 N+1 问题?提前致谢

【问题讨论】:

    标签: sql ruby-on-rails arrays activerecord


    【解决方案1】:

    这是我使用 2 个查询执行此操作的方法,但代码有点复杂。首先我计算 14 个月的所有 earnings 并将它们存储到一个数组中,然后从这些月份中减去 costs 以获得每个月的最终 balance

    def group_by_months
      earnings = orders.order(:created_at).pluck(:earning, :created_at)
      costs = orders.live.order(:created_at).pluck(:cost, :created_at)
    
      result = [0]
      i = 0
      date = Date.today - 13.months
    
      earnings.each do |earning, created_at| 
        if created_at > date
          i += 1
          result[i] = result[i-1]
          date = date + 1.month
        end
        result[i] += earning
      end
    
      i = 0
      date = Date.today - 13.months
    
      costs.each do |cost, created_at| 
        if created_at > date
          i += 1
          result[i] = result[i-1]
          date = date + 1.month
        end
        result[i] -= cost
      end
    
      result
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多