[Ruby] I want to solve the N+1 problem that the data is collated excessively and the operation is heavy

1 minute read

【Overview】


1. Conclusion

What is the 2.N+1 problem?

3. Why is it N+1 problem?

How to solve the 4.N+1 problem

  1. Conclusion

    Use the includes method!


  1. What is the N+1 problem

    This is a problem that occurs when you are making an association. If you make an association without any measures, the A and B databases will Because I will refer to all of them one by one It is a problem that the operation is delayed due to the large amount of processing.

The origin is N+1 because all the records are one record + N records of the contents.


  1. Why it becomes an N+1 problem

    For example, take the following example.

N+1 problem



  class Student <ActiveRecord::Base
 has_many :personals
end

class Personal <ActiveRecord::Base
 belongs_to :student
end

Student_Tabel

id student_name student_age
1 Ayabe 15
2 Sato 16
3 Ito 14

Personal_Tabel

id student_id student_personality
1 1 angry
2 2 gentle
3 3 smart
4 1 shy
5 1 forgetful

In this state,

@students = Student.all

Then Student and Personal After checking one by one with the model and the database, Also when you reflect it in the view with the controller Will do the same.

In this form, (Students table 1 time + data reference frequency 15 times) *2 times It means that it will be processed!


  1. How to solve N+1 problem

    The includes method solves this problem!

For the time being, you can bring in all the related models for the part where you collate them one by one with the model and the database, and collate them one by one when reflecting them in the view with the controller.

Since you do not have to do the same thing twice, the processing becomes lighter. The above is a small amount of data, so it’s not a big deal, but if this number reaches tens of thousands, the processing will differ accordingly.

How to use

@students = Student.includes(:personal)

Model name.includes(: model name you want to associate)

Only!