My confusion stems from this question, where OP has a model like
class Quote < ActiveRecord::Base
has_many :items
def calc_price
sum = 0
#logic for summation
end
end
In the answers, a couple of people have suggested using the sum method directly for calculating the sum of attributes
def total_price
items.sum('price')
end
If I eager load data using Quote.includes(:items).find(:all)
, does the sum happen at the database's end, or does it use the objects already loaded in memory? If it uses the objects already loaded in memory, then the calculations are not being offloaded to the database.
Will it make the database query twice, once to preload, next to sum up the prices?
Extending the same logic to all ActiveRecord::Calculations, Will I hit my database everytime if I do a count
or average
or other such methods?
ActiveRecord::Calculations
(which includessum
,count
,average
) will hit the database even if the items are eager-loaded. For e.g.To check this, run the rails console and log to the console using
ActiveRecord::Base.logger = Logger.new(STDOUT)
. You can then see what db queries are being made for each method.