Skip to main content

Lazy loading in rails – Rails Feature

 Lazy loading in rails – Rails Feature ?

Lazy loading in rails is the amazing feature provided with rails. In console you might have tried to examine how lazy loading in rails actually works. In this tutorial, we will learn about this Rails - Lazy loading feature with examples.
What exactly is Lazy Loading?

As the name suggests the data is loaded in lazy manner (Really!)

i.e. Your database is queried only when data from the database is required for some kind of manipulation in code. You will get more of this after you read how-to of lazy loading below.
How lazy loading works:

Whenever you try to get some data from database,

For example, users is the database table that you have. And you are querying database to get users having age less than 20.

Then, you will write code like,

result = User.where("age < 20")

when above statement is executed, your database is not queries yet(because the resultant data is not required yet).

When you execute following code,

records = result.all

That, you asked for data (All rows from the required data). This is when actually query happens on database and it returns all rows of the result set are returned to results variable. So, results will be array of ActiveRecord's. This is what lazy loading in rails is!

When database is actually queried (end of lazy loading)?

The database is queried when data is required or asked for, in cases like all, first, count, each. These will trigger database load and thus lazy loading will end.
Rails Console and Lazy loading in Rails

This is where you need to be patient. We will take same example as discussed above for examining lazy loading on rails console. We can start rails console by command

rails console or rails c

Getting data from users table having age less than 20. Then you execute command,

result = User.where("age < 20")

And hit enter. Then you will see that console has printed array of ActiveRecord's as result. And thus you might think that query has already been expected on your database and lazy loading hasn't worked quite well. But, this is not what happened. You got this result because rails console inspects last statement that it executes which gives the array of ActiveRecord's.

i.e. If you try

result = User.where("age < 20"); nil
=> nil

Then you will see that rails console has printed nil and not array of ActiveRecord's as a result. As the last statement that is executed was nil.

There is simple way to check whether lazy loading is in place (working correctly) -

Just check the class of result by,

result.class
=> ActiveRecord::Relation

It is ActiveRecord::Relation which means database is actually not queried. And it is just the way console works.

Comments

Popular posts from this blog

Create dynamic sitemap on ruby on rails

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site. It’s basically a XML file describing all URLs in your page: The following example shows a Sitemap that contains just one URL and uses all optional tags. The optional tags are in italics. <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">    <url>       <loc>http://www.example.com/</loc>       <lastmod>2005-01-01</lastmod>       <changefreq>monthly</changefreq>     ...

Omniauth Linked in Ruby On Rails

def get_linkedin_user_data      omniauth = request.env["omniauth.auth"]      dat=omniauth.extra.raw_info      linked_app_key = "xxxxxxx"      linkedin_secret_key = "yyyyyyy"      client = LinkedIn::Client.new(linked_app_key,linkedin_secret_key)      client.authorize_from_access(omniauth['credentials']['token'],omniauth['credentials']['secret'])      connections=client.connections(:fields => ["id", "first-name", "last-name","picture-url"])      uid=omniauth['uid']      token=omniauth["credentials"]["token"]      secret=omniauth["credentials"]["secret"]   #linked user data     omniauth = request.env["omniauth.auth"]      data             = omniauth.info      user_name...

Install Rvm on ubuntu

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev curl -L https://get.rvm.io | bash -s stable source ~/.rvm/scripts/rvm rvm install 2.0.0-p645 rvm use 2.0.0-p645 --default ruby -v rvm gemset create rails3.2.8 rvm gemset use rails3.2.8 gem install rails -v 3.2.8