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”.
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
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.