LoginSignup
1
1

More than 5 years have passed since last update.

N+1問題について

Posted at

概要


SQLクエリが 「データ量N + 1回 」走ってしまい、取得するデータが多くなるにつれて(Nが増えるにつれて)パフォーマンスを低下させてしまう問題。
=> 低下させないようなコードを書くべき



具体例

@posts = Post.all 

@posts.each do |post|
post.user.name
…

などのコードを書くと、、、

起きること
userモデルを事前にローディングしていないので、post.userのたびにクエリが発行される
=> N+1問題


解決法

Eager Loading(事前にデータをローディングしておく)
メソッド includes を利用することで、Postモデルの取得時に、それに関連するUserモデルも取得できる。

@posts = Post.all.includes(:user)



参考「N+1 問題」を検出してくれるライブラリとしてbullet がある



参照

1
1
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
1
1