Tuesday, January 11, 2011

Eager Loading Associations in rails


Eager loading is the mechanism for loading the associated records of the objects returned by Model.find using as few queries as possible.
N + 1 queries problem
Consider the following code, which finds 10 clients and prints their postcodes:


clients = Client.all(:limit => 10)
clients.each do |client|
  puts client.address.postcode
end

This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 ( to find 10 clients ) + 10 ( one per each client to load the address ) = 11 queries in total.


This is possible by specifying the includes method of the Model.find call
Revisiting the above case, we could rewrite Client.all to use eager load addresses:

clients = Client.includes(:address).limit(10)
clients.each do |client|
  puts client.address.postcode
end

The above code will execute just 2 queries, as opposed to 11 queries in the previous case:

SELECT * FROM clients LIMIT 10
SELECT addresses.* FROM addresses
  WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))

No comments:

Post a Comment