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".
group :development do gem 'bullet' end
bundle install. Set.
If you use bullet, a warning screen and log will appear.
For example, make the relationship between users and posts one-to-many.
class User < ApplicationRecord has_many :posts end
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.