Knowledge for the World

scout

The N+1 problem occurs when at least two objects are stored in a database with a one-to-many relationship and queries are performed against the "one" table, then separately n number of times against the related object, n being the number of related objects.To illustrate this, I'll use the analogy of a meal website and a page where you wish to display the meals. In the controller:@meals = Meal.where(status=1) # approximate query: SELECT * FROM meals WHERE status = 1;In the view:<% @meal.each do |meals| %> <div class="meal-row"> <h4><%= meal.name %><br /> <%= link_to meal.user.username, user_path(meal.user.username) %> <%# approximate query: SELECT * FROM users WHERE user.id = {{ meal_id }}; %> </h4> <p><%= meal.description %></p> <%= link_to 'Cook This Now', meal %> </div> <% end %>Notice how we're creating a link to meal.user.username.To approximate the queries used in this page, we have the following:SELECT * FROM meals WHERE status = 1; # 1 time, yielding n rows SELECT * FROM users WHERE user.id = {{ meal_id }}; # n timesThe ORM in Rails should do a lot of work to minimize the net slowness of this problem such as database indexing and caching template fragments, but nothing will change the fact that you are querying the database in a loop.Now let's take a look at how to find these in your code and how to get rid of them.