3

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?

4

1 に答える 1