The number of SQL issued increases in proportion to the number of data to be handled. This issue affects performance and should be resolved. As an analogy I often hear, the N + 1 problem is that when you buy a lot of items for shopping, you only pay for each item.
A library that finds "N + 1 problems".
Gemfile
group :development do
  gem 'bullet'
end
bundle install. Set.
config/environments/development.rb
Rails.application.configure do 
 #Omitted on the way
  config.after_initialize do
    Bullet.enable = true #Enable Bullet gem
    Bullet.alert = true #Pop up JavaScript alert in your browser
    Bullet.bullet_logger = true #Bullet log file (Rails).root/log/bullet.log)
    Bullet.console = true #Warning browser console.Record in log
    Bullet.rails_logger = true #Add alerts directly to Rails logs
  end
end
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
Outputs 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 such logs and warning messages. Therefore,
Post.inculudes(:user).each do |post|
  puts post.user.name
end
If so, it's OK.
Recommended Posts