不要的ActiveRecord ::计算与预先加载进行多个数据库查询? [英] Do ActiveRecord::Calculations with eager loading make multiple database queries?

查看:115
本文介绍了不要的ActiveRecord ::计算与预先加载进行多个数据库查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的困惑来自这个问题,其中OP有一个像

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

如果我急于加载数据使用 Quote.includes(:项目).find(:所有),并总和发生在数据库的结束,或者它使用对象在内存中加载的?如果使用存储器已经加载的对象,然后计算不被卸载到数据库中。

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.

会不会使数据库查询两次,第一次为preLOAD,总结一下价格下?

Will it make the database query twice, once to preload, next to sum up the prices?

扩展相同的逻辑来所有的ActiveRecord ::计算,我会打我的数据库每次如果我做了计数平均或其他类似的方法呢?

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 ::计算(其中包括计数平均)将访问数据库,即使项目都渴望加载。对于例如。

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

要检查,运行轨道控制台,并使用的ActiveRecord :: Base.logger = Logger.new(标准输出)登录到控制台。然后,您可以看到正在为每种方法有什么的数据库查询。

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.

这篇关于不要的ActiveRecord ::计算与预先加载进行多个数据库查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆