简体   繁体   中英

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 .

For example, I have users table with accounts and patients tables, that both 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 = 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:

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. So what is #includes for? It decides for you which way it is going to be. You let Rails handle that decision.

Check this guide for great information on includes/eager_load/preload in rails: http://blog.arkency.com/2013/12/rails4-preloading/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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