Discover how a tiny change can stop your app from drowning in slow database calls!
Why Eager loading (N+1 prevention) in Ruby on Rails? - Purpose & Use Cases
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.
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.
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.
posts = Post.all
posts.each { |post| puts post.author.name }posts = Post.includes(:author)
posts.each { |post| puts post.author.name }You can efficiently load related data in one go, making your app faster and more scalable without extra effort.
On a social media feed, showing each user's profile info alongside their posts without slowing down page load.
Manual loading causes many slow database queries.
Eager loading fetches related data upfront in fewer queries.
This improves app speed and user experience significantly.