Check out my latest project called Rails UI 🎨

March 16, 2023

Rails Quick Tips - 06 - N+1 queries and the Bullet gem

In Ruby on Rails, a common issue developers face is n+1 queries, which occur when an application sends multiple queries to the database instead of combining them into a single query. This can significantly decrease application performance, as each query adds to the overall load on the database.

To avoid n+1 queries, developers can use the Bullet gem, which is a Ruby gem that provides a way to detect and eliminate n+1 queries. Here are the steps to use the Bullet gem:

Install the Bullet gem by adding it to your Gemfile and running bundle install.

In your Rails application, enable the Bullet gem by adding the following line of code to your application.rb file:

config.after_initialize do
  Bullet.enable = true
  Bullet.bullet_logger = true

This code initializes the Bullet gem and enables logging of n+1 queries.

Run your Rails application and perform actions that trigger queries to the database. When an n+1 query is detected, Bullet will log a message to the console, indicating which queries are causing the issue.

To resolve the n+1 query issue, you can use eager loading to preload associations in a single query. For example, if you have a model called "Post" that has many "comments," you can use eager loading to load all comments for all posts in a single query like this:

@posts = Post.includes(:comments)

This will preload all comments for all posts in a single query, eliminating the need for n+1 queries.

In conclusion, n+1 queries can be a common issue in Ruby on Rails applications. Still, developers can quickly detect and eliminate these queries by using the Bullet gem and eager loading, improving application performance and reducing database load.

Several other gems are out in the wild to help with n+1 queries.

Here are a few

  • Rack-mini-profiler: This gem provides profiling for Rails applications, including detecting n+1 queries. It can also help identify slow requests and provide suggestions on how to optimize them.

  • Fasterer: Fasterer is a gem that provides a set of rules for optimizing Ruby code. One of these rules detects n+1 queries in ActiveRecord models and suggests using eager loading.

  • ActiveRecord Doctor: This gem provides various diagnostic tools for ActiveRecord models, including detecting n+1 queries. It can also help optimize database schema, indexes, and queries.

Est. reading time: 2 minutes
Stats: 1,202 views



Part of the Rails Quick Tips collection