简体   繁体   English

急于使用ActiveRecord从User表中加载单个条目以及相关的belong_to记录

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

Is it possible to eager load a specific entry from the user table, as well as all associated tables attached via belong_to . 是否有可能急切地希望从用户表以及通过belong_to附加的所有相关表中加载特定条目。

For example, I have users table with accounts and patients tables, that both belong_to :user . 例如,我有users用表accountspatients表,这两个belong_to :user If I wanted to grab a specific User table entry and eager_load the associated tables, akin to something like this: 如果我想获取特定的User表条目并eager_load关联的表,则类似于以下内容:

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

How can I do it ? 我该怎么做 ?

You were close. 你近了 Try putting the associations in an array within the eager_load call as shown below: 尝试将关联放在eager_load调用中的数组中,如下所示:

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

Now that you have included the associated tables and then found your user you can call any attributes from those other tables on the user without firing another query from the database. 现在,您已经包含了关联的表,然后找到了您的用户,您可以从用户的那些其他表调用任何属性,而无需从数据库中触发另一个查询。 For example once that is run you can do: 例如,一旦运行,您可以执行以下操作:

all_user_accounts = user.accounts

This will not fire a query in the database but instead be loaded from memory. 这不会在数据库中触发查询,而是从内存中加载。

If you use #eager_load you are doing one query whereas includes will do it in one or two depending on what it deems necessary. 如果您使用#eager_load,则您将执行一个查询,而include将根据其认为需要一两个查询。 So what is #includes for? 那么#includes的作用是什么? It decides for you which way it is going to be. 它为您决定它将是哪种方式。 You let Rails handle that decision. 您让Rails处理该决定。

Check this guide for great information on includes/eager_load/preload in rails: http://blog.arkency.com/2013/12/rails4-preloading/ 请查看此指南,以获取有关rails中的include / eager_load / preload的详细信息: http ://blog.arkency.com/2013/12/rails4-preloading/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM