What is the 2.N+1 problem?
3. Why is it N+1 problem?
How to solve the 4.N+1 problem
Use the includes method!
- 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.
- Why it becomes an N+1 problem
For example, take the following example.
class Student <ActiveRecord::Base has_many :personals end
class Personal <ActiveRecord::Base belongs_to :student end
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!
- 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)