My Journey Optimising a Rails Application Part-1

Finished developing a rails application, My next step was optimising the application:

First include the ‘rack-mini-profiler’ gem in your development group. It provides a handy little dialogue which tells you how much time each view is taking to load and the number of sql queries it is performing.


First optimisation and the most common one I could find in my application was that my application was making unnecessary db calls due to rails lazy-loading.

ex:- If you had the following schema:

#subject.rb
belongs_to course
#course.rb
has_many subjects
belongs_to university
#university.rb 
has_many courses

If you want to display list of all the subjects in subjects#index view along with the course name they belong to, rails will query the courses table for each subject you display because of lazy-loading. This is unnecessary ( If you have 10 subjects rails will do 11 queries to populate the data for the view). To force rails to load the list of subjects along with the courses to which it belongs to at the time of loading, we force rails to use eager-loading.

Eager-loading:

You should load the subjects as follows:

@subjects = Subject.eager_load(:course)

This forces rails to perform join between subject and course and load it. Now rails performs only one db query initially. When it requires the course related to a subject it looks for the object in its memory rather then performing additional db query ( so it performs only 1 query to fetch all the data required for the view).


If you notice that it is very common that you are eager loading course when every you are querying for a subject then you can force rails to load the course by default.

Go to your subject.rb file and add the following piece of code:

# subject.rb
default_scope { eager_load(:course) }

If you want to eager_load multiple associations, you can do like this:

#course.rb
default_scope { eager_load( :subjects, :university) }

If you need to eager_load nested associations by passing it as an hash:

#subject.rb
default_scope { eager_load(:course => :university) }
Show your support

Clapping shows how much you appreciated NG Sai Prasanth’s story.