Ruby on rails ActiveRecord::带即时加载的计算是否会进行多个数据库查询?
我的困惑源于OP的模型Ruby on rails ActiveRecord::带即时加载的计算是否会进行多个数据库查询?,ruby-on-rails,ruby,activerecord,eager-loading,Ruby On Rails,Ruby,Activerecord,Eager Loading,我的困惑源于OP的模型 class Quote < ActiveRecord::Base has_many :items def calc_price sum = 0 #logic for summation end end 如果我使用Quote.includes(:items).find(:all)加载数据,那么求和是发生在数据库的末尾,还是使用已加载到内存中的对象?如果它使用已加载到内存中的对象,则计算不会卸载到数据库中 它会让数据库查询两次,一次预加载,
class Quote < ActiveRecord::Base
has_many :items
def calc_price
sum = 0
#logic for summation
end
end
如果我使用Quote.includes(:items).find(:all)
加载数据,那么求和是发生在数据库的末尾,还是使用已加载到内存中的对象?如果它使用已加载到内存中的对象,则计算不会卸载到数据库中
它会让数据库查询两次,一次预加载,下一次汇总价格吗
将相同的逻辑扩展到所有人,如果我每次执行
计数
或平均值
或其他类似方法,我是否会命中数据库?ActiveRecord::Calculations
(包括总和
,计数
,平均值
)将命中数据库,即使项目已加载。例如
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
要检查这一点,请运行rails控制台并使用
ActiveRecord::Base.logger=logger.new(STDOUT)
登录控制台。然后,您可以看到对每个方法进行了哪些db查询。重要的不是它命中数据库只是求和,而是一次命中将返回一个值。它比你能做的任何事情都要快,而且可能比在内存中迭代数据要快。
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