TODO N+1

https://code.tutsplus.com/articles/improving-the-performance-of-your-rails-app-with-eager-loading--cms-25018

Introduction

Ruby on Rails ORM has lazy loading enabled.

Example

#  Post Model
class Post < ActiveRecord::Base
    belongs_to :author
end

#  Author Model
class Author < ActiveRecord::Base
    has_many :posts
end
# Controller
class PostsController < ApplicationController
    def index
        @posts = Post.order(created_at: :desc)
    end
end

Case 1: Default - lazy loading

N+1

Case 2.1: preload - eager loading / separated queries

  1. No N+1

  2. Fail @ order posts by author name

  3. Fail @ find posts by author name

Case 2.2: eager_load - eager loading / one query

order posts by author name

find posts by author name

single query and LEFT OUTER JOINcan also be very expensive.

Case 2.3 includes - smarter

(same as preload)

order posts by author name (same as eager_load)

find posts by author name (same as eager_load)

Last updated

Was this helpful?