LoginSignup
0
0

More than 3 years have passed since last update.

N+1問題を解決ゾロリ ❏Rails❏

Last updated at Posted at 2019-11-26

【結論】includesを使う

データベースにアクセスする回数を減らそう

データを取ってくる際にSQLというものが発行されます。

アソシエーションを組んでいる場合、子要素のデータを取ってくる時もあるでしょう。
例えばこんな時

index.html.haml
- @tweets.each do |tweet|
  = tweet.text
  = tweet.user.nickname

tweetsテーブルとusersテーブルからデータを取ってきてます
この時SQLは通常(tweetsテーブル)+1回(usersテーブル)発行されてしまいます。

SQLが多いと処理が重くなるので、1回で関連するデータを一気に持ってきちゃおうぜ!って話です。

UserモデルとTweetモデルが以下のアソシエーションを組んでいるとします。

user.rb
has_many :tweets
tweet.rb
belongs_to :user


【tweetsコントローラーを編集】

includes (:モデル名)
これで一気に関連データまで取ってくることができます。

tweets_controller.rb
def index
  @tweets = Tweet.includes(:user)  #allは省略可
end

これでN+1問題はバッチリ解決です!



ではまた!

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