LoginSignup
0
0

More than 1 year has passed since last update.

【N+1問題】ループ処理の中でクエリを実行しない!

Posted at

N+1問題

ループ処理の中でクエリを実行しない!
大量のクエリが発行されるのでめちゃくちゃ重くなるので、
ループを実行する前にあらかじめデータ取得しておく。

良くない例

books = Book.all

book_names = []
books.each do |book|
  book_names << BookSynopsis.find_by(book_id: book.id).name
end

良い例

book_synopsis = Book.includes(:book_synopsis)

book_names = []
book_synopsis.each do |book_synopsis|
  book_names << book_synopsis.name
end

参考

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