0
0
Ruby on Railsframework~5 mins

Database query optimization in Ruby on Rails

Choose your learning style9 modes available
Introduction

Database query optimization helps your Rails app get data faster. It makes your app feel quicker and saves server work.

When your app loads pages slowly because it asks the database too many times.
When you want to show related data without extra waiting.
When you notice your app uses a lot of memory or CPU because of big database queries.
When you want to reduce the number of database calls to save resources.
When you want to avoid loading unnecessary data from the database.
Syntax
Ruby on Rails
Model.where(condition).includes(:association).select(:fields).order(:field)
Use includes to load related data in one query and avoid extra database calls.
Use select to get only the fields you need, making queries faster.
Examples
Loads active users and their posts in one go to avoid extra queries when accessing posts.
Ruby on Rails
User.where(active: true).includes(:posts)
Gets only the post ID and title, sorted by newest first, which is faster than loading all fields.
Ruby on Rails
Post.select(:id, :title).order(created_at: :desc)
Finds comments where the user is active by joining tables in one query.
Ruby on Rails
Comment.joins(:user).where(users: {active: true})
Sample Program

This controller action loads all published articles and their authors in one database query. This avoids asking the database again for each article's author, making the page load faster.

Ruby on Rails
class ArticlesController < ApplicationController
  def index
    # Load articles with their authors to avoid extra queries
    @articles = Article.includes(:author).where(published: true).order(published_at: :desc)
  end
end
OutputSuccess
Important Notes

Always check your queries with Rails console or logs to see how many database calls happen.

Use includes for associations to prevent the N+1 query problem.

Be careful not to load too much data; select only what you need.

Summary

Optimizing queries makes your app faster and saves server resources.

Use includes to load related data efficiently.

Use select and where to get only needed data.