Friday, March 7, 2008

Eager and Lazy Loading in Rails


How do you control how much data you want to be loaded from database
when you have your objects tied up with Rails Associations?



For Instance, in the Social Networking Context, I need to show just a few of a
person's friends on his home page and provide a see all link which
takes him to a page which then shows all, possibly with pagination.


Eager Loading :



http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html



http://matthewman.net/2007/01/04/eager-loading-objects-in-a-rails-has_many-through-association/



http://www.travisonrails.com/2007/02/18/Rails-eager-loading-of-associations



http://www.theserverside.com/tt/articles/article.tss?l=RailsHibernate



Lazy Loading :



http://weblogs.asp.net/fbouma/archive/2007/04/16/more-on-lazy-loading-vs-pre-loading-in-o-r-mapping-scenarios.aspx



http://ayende.com/Blog/archive/2007/04/15/Lazy-loading-The-Good-The-Bad-And-The-Evil-Witch.aspx



When you have an object associated with many objects like a User has
many Friends and you want to display a list as in Orkut you fire as
many queries as there are friends, plus one for the object itself.



To load all the relevant data at once it is better to use the :include option.



user = User.find(:all, :include=> :friends) to find all users with friends in a single query.

Different variations of the find call can be used.

An approach is to write a method in your model for User which makes this query and invoke that from your controller. To make this method reusable, you can make it expect a parameter which indicates how many friends to load, but set the default value to 0 so that if nothing is passed, you can expect to load :all.

Hence the same method is invoked in the action which populates both views - the semi list as well as the full list.

Kapish?






0 comments: