使用 ActiveRecord 从用户 table 和关联的 belongs_to 记录中急切加载个人条目

Eager loading individual entry from User table and associated belongs_to records using ActiveRecord

是否可以预先加载用户 table 的特定条目,以及通过 belong_to 附加的所有关联 table。

例如,我有 users table 和 accountspatients table,两者都是 belong_to :user。如果我想获取特定的用户 table 条目和 eager_load 关联的 tables,类似于这样的事情:

user = User.find_by_email("testemail@here.com").eager_load(:accounts, :patients)

我该怎么做?

你很接近。尝试将关联放在 eager_load 调用中的数组中,如下所示:

user = User.includes([:accounts, :patients]).find_by(email: "testemail@here.com")

现在您已经包含了相关联的表,然后找到了您的用户,您可以从用户的其他表中调用任何属性,而无需从数据库中触发另一个查询。例如一旦是 运行 你可以这样做:

all_user_accounts = user.accounts

这不会在数据库中触发查询,而是从内存中加载。

如果您使用#eager_load,您将执行一次查询,而包含将根据它认为必要的情况分一或两次执行。那么#includes 有什么用呢?它为你决定它会是哪种方式。你让 Rails 处理那个决定。

查看本指南以获取有关 rails 中 includes/eager_load/preload 的重要信息: http://blog.arkency.com/2013/12/rails4-preloading/