Eager Loading - Nextfave/simply_stored GitHub Wiki

Eager loading is the mechanism for loading the associated records of the objects using as few queries as possible. Reducing the number of queries made to the database can speed up application significantly. So, eager loading is a great technique to boost up performance of an application.

N+1 queries problem

Consider the following example:

project = Project.find('70975ffcb12629a287f5a9fe6b84257c')

issues = project.issues

issues.each do |issue|
  puts issue.owner.email
end

Let's say the project has total 200 issues. In that case, the above snippet produces at least 202 database calls. Project.find makes 1 call, project.issues makes another 1 call and the block for issues.each makes 200 calls (if all couchdb views exist).

The N+1 query problem can be solved by eager loading associated objects.

Let's update the above snippet:

project = Project.find('70975ffcb12629a287f5a9fe6b84257c')

issues = project.issues(:eager_load => [:owner])

issues.each do |issue|
  puts issue.owner.email
end

Now the block for issues.each doesn't make any queries to the database. So, we have only 3 database calls.

There are two more approaches for eager loading.

With finder methods:

Issue.all(:eager_load => [:owner])

If you have already an array of objects you can use a helper method for the same purpose.

SimplyStored::Couch::Helper.eager_load(issues, [:owner])

Note: Currently we can only eager load belongs_to relations. Unlike ActiveRecord there is no way to eager load has_many associations. That means we can't do the following:

issues = project.issues(:eager_load => [:comments])