Do ActiveRecord::Calculations with eager loading m

2019-05-15 00:13发布

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?

1条回答
戒情不戒烟
2楼-- · 2019-05-15 00:31

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.

查看更多
登录 后发表回答