2016-07-30 5 views
0

UserOrderの2つのモデルがあります。毎月の残高を配列で取得するグラフを生成する必要があります。私のOrderテーブルには、earningscostsがあります。ここで私はいくつかのこれまで出ているものです:クエリの件数N + 1

user.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の問題に取り組むためにこれを行うためのよりよい方法はありますか?前もってありがとう

答えて

0

これは2つのクエリでこれを行う私の方法ですが、コードはもう少し複雑です。まず、earningsを14ヶ月間計算し、配列に格納してから、これらの月から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 
関連する問題