Closed miminashi closed 2 years ago
archive#indexにアクセスしたときのクエリの数を数えてみたら、レコードが7つある状態で15回クエリが発行されていた。
https://api.rubyonrails.org/classes/ActiveStorage/Attached/Model.html#method-i-has_one_attached
with_attached_foo
を使うとよさそう
モデルが以下のようになっているとき、
has_one_attached :thumbnail
以下のようにすると関連するActiveStorageのレコードを同時にまとめてとってきてくれるようだ。
Archive.with_attached_thumbnail
複数のAttachedがある場合は、以下のようにすればいいっぽい。
Archive.with_attached_thumbnail.with_attached_video
ただし、joinされるわけではなく、Attachedごとに別々のクエリになるようだった。 これをEager Loadingというらしい。
体感としてわかる程度に改善できたようなのでクローズ
N+1クエリになってしまってる
N=2 の場合
N=20くらい の場合
このへんでも言及されているようにscopeかなにかをつかってjoinされるようにする。 https://railsguides.jp/active_storage_overview.html#%E9%81%85%E5%BB%B6%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF%E3%81%A8%E3%82%A4%E3%83%9F%E3%83%87%E3%82%A3%E3%82%A8%E3%82%A4%E3%83%88%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF