0
User
とOrder
の2つのモデルがあります。毎月の残高を配列で取得するグラフを生成する必要があります。私のOrder
テーブルには、earnings
とcosts
があります。ここで私はいくつかのこれまで出ているものです:クエリの件数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の問題に取り組むためにこれを行うためのよりよい方法はありますか?前もってありがとう