0
0
Ruby on Railsframework~3 mins

Why Eager loading (N+1 prevention) in Ruby on Rails? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny change can stop your app from drowning in slow database calls!

The Scenario

Imagine you have a list of blog posts, and for each post, you want to show the author's name. You write code that fetches all posts, then for each post, you ask the database for the author details separately.

The Problem

This means if you have 10 posts, you make 1 query for posts plus 10 more queries for authors. This slows down your app and makes the database work too hard, causing delays and frustration.

The Solution

Eager loading lets you tell Rails to fetch all posts and their authors in just two queries upfront. This avoids asking the database repeatedly and makes your app faster and smoother.

Before vs After
Before
posts = Post.all
posts.each { |post| puts post.author.name }
After
posts = Post.includes(:author)
posts.each { |post| puts post.author.name }
What It Enables

You can efficiently load related data in one go, making your app faster and more scalable without extra effort.

Real Life Example

On a social media feed, showing each user's profile info alongside their posts without slowing down page load.

Key Takeaways

Manual loading causes many slow database queries.

Eager loading fetches related data upfront in fewer queries.

This improves app speed and user experience significantly.