0
0

More than 1 year has passed since last update.

ActiveModelSerializerで発生したN+1問題を解決

Posted at

前提

UserとPostは1対Nの関係

class Post < ApplicationRecord
 belongs_to :user
end
class User < ApplicationRecord
 has_many :posts, dependent: :destroy
end

解消前

テストログを見るとserializerが走ったときにN+1問題が発生していた。

def index
  posts = current_user.posts
  render json: posts
end

解消後

def index
  posts = current_user.posts.preload(:user)
  render json: posts
end

scopeに切ると他でも使えてベター

model.rb
scope :preload_user, -> { preload(:user) }
def index
  posts = current_user.posts.preload_user
  render json: posts
end

参考

preloadとeager_loadの使い分けは下記の記事を参照

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0