[RUBY] I want to solve the N + 1 problem where the data is collated excessively and the operation becomes heavy.

【Overview】

1. Conclusion </ b>

2. What is the N + 1 problem </ b>

3. Why is it an N + 1 problem? </ B>

4. How to solve the N + 1 problem </ b>

  1. Conclusion

Use the includes method </ b>!


2. What is the N + 1 problem?

This is a problem that occurs when you are associating. If you form an association without taking measures, A database and B database will be To refer to all of them one by one This is a problem that requires a lot of processing and delays the operation.

The origin is N + 1 because all the records are combined into 1 + N records inside.


3. Why is it 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 collating one by one with the model and the database, Also, when reflecting on the view with the controller I will do the same.

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


4. How to solve the N + 1 problem

The includes method </ b> solves this problem!

For the time being, you can bring all the related models and match them one by one when reflecting them in the view with the controller.

You don't have to do the same thing twice, which makes the process lighter. The above is a small amount of data, so it's not a big deal, but if there are thousands or tens of thousands of data, the processing will be different.

How to use

@students = Student.includes(:personal)

Model name.includes(:紐づけたいModel name)

Only!


Recommended Posts