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.