Kamis, 15 Desember 2011

Eager Loading

When we are building a website, a small website, it wont be feel slow, if we are querying a large of data from database.

But.. if you re building a large scale rails application. This is one of the methods you have to use, Eager Loading

Eager loading is One way to improve performance is to cut down on the number of SQL queries.
It will improve query on rails application

I dont quite understand how rails do it.
But simple, programmer doesnt have to know all the things(code) that written down. lol.

This is the example

      class Post < ActiveRecord::Base
           belongs_to :author
           has_many   :comments

Then you are querying it on the view.

for post in Post.all
  puts "Post:            " + post.title
  puts "Written by:      " + post.author.name
  puts "Last comment on: " + post.comments.first.created_on

What happened?
they will querying to comments table, as much as data on the posts tables.
So it's really painfull.

So with code below :

for post in Post.find(:all, :include => :author)

There will be just 1 query to the database.

And it will make your application lightener..

0 komentar:

Posting Komentar

Copyright 2009 ruby on rails. Powered by Blogger
Blogger Templates created by Deluxe Templates
Wordpress by Wpthemescreator