Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do ActiveRecord::Calculations with eager loading make multiple database queries?

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?

like image 808
Anshul Goyal Avatar asked Jan 24 '26 18:01

Anshul Goyal


1 Answers

ActiveRecord::Calculations (which includes sum, count, average) will hit the database even if the items are eager-loaded. For e.g.

 quotes = Quote.includes(:items).find(:all)
 # two queries one to fetch quotes and one to fetch all associated items

 items = quotes.first.items
 # no query as items are eager loaded

 total_price = quotes.first.items.sum(:price)
 # one query to get sum of item prices for the first quote
 # summation is done by the database

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.

like image 135
tihom Avatar answered Jan 27 '26 08:01

tihom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!