ActiveRecord 查询中的“包含"和“预加载"之间有什么区别? [英] What's the difference between “includes” and “preload” in an ActiveRecord query?

查看:16
本文介绍了ActiveRecord 查询中的“包含"和“预加载"之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找 ActiveRecord 对象的 includes() 和 preload() 的比较.谁能解释一下区别?

I'm struggling to find a comparison of includes() and preload() for ActiveRecord objects. Can anyone explain the difference ?

推荐答案

Rails 有两种方法可以避免 n+1 问题.一个涉及创建一个基于大连接的查询来拉入您的关联,另一个涉及为每个关联创建一个单独的查询.

Rails has 2 ways of avoiding the n+1 problem. One involves creating a big join based query to pull in your associations, the other involves making a separate query per association.

当你做 includes 时,rails 决定你使用哪种策略.它默认为单独的查询方法(预加载),除非它认为您正在使用条件或订单中的关联列.由于这仅适用于连接方法,因此使用它代替.

When you do includes rails decides which strategy to use for you. It defaults to the separate query approach (preloading) unless it thinks you are using the columns from the associations in you conditions or order. Since that only works with the joins approach it uses that instead.

Rails 的启发式方法有时会出错,或者您可能有特定原因偏爱一种方法而不是另一种方法.preload(及其配套方法 eager_load)允许您指定希望 Rails 使用的策略.

Rails' heuristics sometimes get it wrong or you may have a specific reason for preferring one approach over the other. preload ( and its companion method eager_load) allow you to specify which strategy you want rails to use.

这篇关于ActiveRecord 查询中的“包含"和“预加载"之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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