[Ruby] [N+1 question]

less than 1 minute read

What is the ##N+1 problem? A problem that occurs when associating models with an association.

For example, if the user and the post are linked in an application such as Twitter, When the list of posts is displayed on the top page, if the database is accessed each time to search for the user associated with each post, the performance of the application will decrease.

If you have 10,000 posts, you have to access the database 10,000 times.

This problem is called the N+1 problem.

The method to solve this problem is

include method

Method called.

This method accesses the database every time and searches the linked data, Get all the data in one go.

Therefore, even if you have 10,000 posts, you can access the database “once.


It can be used if includes (: model to be linked) in the process content of index action like the image above.

This will not degrade performance when displaying tweets etc. no matter how many posts there are.