Mark Chavez
eat. sleep. repeat. 👾 coding, ⌨️ keyboarding, 🚴🏼 cycling.
Rails ActiveRecord: Lazy vs Eager Loading 08/02/2024

Lazy loading - loading queries on demand.

Eager loading - loading queries immediately.

Lazy loading can possibly produce an N+1 query if mishandled.

# N+1 - for each post, it counts all comments.
Post.all.each do |post|
post.comments.count
end

One way of solving this inefficient query is as follows:

Post.includes(:comments).each do |post|
post.comments.size
end

Notice the use of size instead of count. Since we’ve preloaded comments, there’s no need to use count as this will perform another SQL query.

Another type of eager loading aside from includes, is the use of preload.

Strict Loading

You can force your Rails app, or to a smaller extent, an individual query to use eager loading by applying strict_loading.

posts = Post.strict_loading.all

# will raise an exception because lazy loading is found
posts.each do |post|
post.comments.count
end