Saturday, 21 June 2014

Three ways to do eager loading in Rails

There are three ways to do eager load in rails.they are:

1. includes
2. preload and
3. eager_load

includes delegates the job to preload or eager_load depending on the presence or absence of condition related to one of the preloaded table.

preload is using separate DB queries to get the data.

eager_load is using one big query with LEFT JOIN for each eager loaded table.

In Rails 4 you should use #references combined with includes if you have the additional condition for one of the eager loaded table.

  Typically, when you want to use the eager loading feature you would use the includes method, which Rails encouraged you to use since Rails2 or maybe even Rails1 ;). And that works like a charm doing 2 queries:
    
User.includes(:addresses)
#  SELECT "users".* FROM "users" 
#  SELECT "addresses".* FROM "addresses" WHERE "addresses"."user_id"
IN (1, 2)
doing one query. So what is #includes for? It decides for you which 
way it is going to be.
User.preload(:addresses)
#  SELECT "users".* FROM "users" 
#  SELECT "addresses".* FROM "addresses" WHERE "addresses"."user_id" 
IN (1, 2)
 Apparently #preload behave just like #includes.
If you use #preload, it means you always want separate queries. If 
you use #eager_load you arelet Rails handle that decision.What is
query conditions. Let's see an example where #includes delegates to 
#eager_load so that there is one big query only.the decision based
on, you might ask. It is based on

No comments:

Post a Comment