Rails foundationSort Order

Rails: Solving N+1 with Includes

N+1 is a problem that plauges every rails app I've ever built or inheritted. However this need not be the case. Most of the time, people don't fix it because they don't want to optimize prematurely. However when the solution is simple, we need to take it into account and be aware of what it's doing to our application.

Implementing the Fix

# app/controllers/admin/posts_controller.rbclass Admin::PostsController < Admin::BaseController  def index    @posts = scoped_posts      .includes(:tags)      .order("created_at DESC")      .page(params[:page]).per(10)  end    # ...end

We should now be able to see the difference in our rails server output. We have another N+1 problem related to counting the comments, in the next episode we'll solve it using counter cache.