[ ActiveRecord ] includes

overview

Eager loading and Lazy loading

 

declaration

Client model has the relation has_many :address
Address model has the relation belongs_to :client

1 + N queries ( eager loading ) 

clients = Client.limit(10)

clients.each do |client|
puts client.address.postcode
end

The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = 11 queries in total.

Solution to reduce to 2 queries ( lazy loading )

clients = Client.includes(:address).limit(10)

clients.each do |client|
puts client.address.postcode
end
SELECT * FROM clients LIMIT 10
SELECT addresses.* FROM addresses
WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))

ref : http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations,

https://www.spritle.com/blogs/2011/03/17/eager-loading-and-lazy-loading-in-rails-activerecord/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s