0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rails で N+1 を解消したいのに関連先が取れない

Last updated at Posted at 2023-05-29

やりたいこと

N+1 を解消するのには includeseager_loadpreload を使えばいいのは分かったしその違いも分かった。
でも、関連付けが取れない。

Author が books を has_many で book も reviews を has_many してるとき、普通に Author.books.reviews を取ったら N+1 になるじゃないですか。
だから以下のように書きたい。でも書けない。

Author.joins(:books).includes(:reviews)

みたいに書きたいんだけど、そうすると

ActiveRecord::AssociationNotFoundError: Association named 'reviews' was not found on Author; perhaps you misspelled it?
Did you mean? books

なんて感じのエラーになってしまう。
どう書けばいいんだろう?

正解

Author.includes(books: :reviews)

を見れば、複数の関連付けを取りたい場合なども分かります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?