お使いのブラウザはサポート対象外です。

2021年07月14日(水) の日報

2

Add available_records argument to Associations::Preloader by dinahshi · Pull Request #42654 · rails/rails

  • preloadで、予め取得していたオブジェクトをpreloadした結果としてアサインできる
  • 最高便利!と思ったがhas_oneやbelongs_toの関連しか使えないとのこと
  • サンプルコードがややおかしい(all_authorsって複数の値をとり得ると思うのにbelongs_to関連にアサインしている)
  • 複数レコードに対してpreloadしたい場合はどう書くんだこれ(eachで一つずつ実行するのかな…)
  • 謎が多いので後で調べるぞ
# Assume we have post and all_authors loaded elsewhere
comment = Comment.last
post = Post.find_by(id: comment.post_id)
all_authors = Author.all.to_a

# Previously this would have executed two queries to fetch post and author.
Preloader.new([comment], [:post, :author]).call

# Using the available_records parameter, this executes zero queries since
# the associated records are already in memory.
Preloader.new([comment], [:post, :author], available_records: [post, all_authors]).call