LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】【Ruby】find_by_sql でも preload したいとき

Posted at

はじめに

find_by_sql を使って複雑なSQL文を書いたが、N+1を避けるために preloadしたい時がある。

結論

下記のように書けばOK

records = User.find_by_sql(...)
ActiveRecord::Associations::Preloader.new.preload(records, :like)

下記はpreloadが無視されるのでダメ

User.preload(:like).find_by_sql(...)

注意点

Rails7 で記法が下記のように変わる

records = User.find_by_sql(...)
ActiveRecord::Associations::Preloader.new(records: records, associations: :like).call

参考

https://www.natsuneko.blog/entry/2017/04/18/find_by_sql-preload
https://michiomochi.com/blog/rails-v6047-to-v7023

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