[Ruby] [Beginner] Discovered N+1 problem! How to use Bullet

1 minute read

What is the ##N+1 problem? The number of SQL issued increases in proportion to the number of data handled. This problem affects performance, so it is a problem I want to solve. As an analogy to hear well, the N+1 problem is that when you buy a lot of items from shopping, you can only pay one point at a time.

What is bullet

It is a library that finds “N+1 problem”.

Introduction method

Gemfile


group :development do
  gem'bullet'
end

bundle install. Set.

config/environments/development.rb



Rails.application.configure do
 # Omitted

  config.after_initialize do
    Bullet.enable = true #Enable Bullet gem
    Bullet.alert = true # Pop up JavaScript alert in browser
    Bullet.bullet_logger = true #Bullet Log file (Rails.root/log/bullet.log)
    Bullet.console = true #Warning logged in browser console.log
    Bullet.rails_logger = true # Add warning directly to Rails log
  end
end

Solution

If you use bullet, a warning screen and log will appear.

For example, make the relationship between users and posts one-to-many.

user.rb


class User <ApplicationRecord
  has_many :posts
end

post.rb


class Post <ApplicationRecord
  belongs_to :user
end

Output the user name for all posts.

Post.all.each do |post|
  puts post.user.name
end
USE eager loading detected
Psot => [:user]
Add to your finder::incluedes => [:user]

You will see logs and warning messages like this. Therefore,

Post.inculudes(:user).each do |post|
  puts post.user.name
end

Then it is OK.