0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】ActiveRecordの遅延評価

Posted at

はじめに

ActiveRecordの遅延評価について調べた内容を整理します。

ActiveRecordの遅延評価とは

値が必要とされるまでSQLの処理を実行しない仕組み

ActiveRecord::Relation

relation = UserBook.where(user: user)
relation.class
# => UserBook::ActiveRecord Relation
  • この時点でSQLは発行していない
  • relationに入っているのはActiveRecord::Relationオブジェクト
  • SQLをどう組み立てるかという情報をツリー構造のように蓄積・保持することができる

SQLが実行されるタイミング

データを必要とする操作をしたとき
to_a each first/last map select countなど

メリット

1. パフォーマンス向上

必要な時だけSQLを実行する=無駄なクエリを避ける

relation = UserBook.where(user: user) # SQLはまだ発行されない

relation.each do |user_book|          # ここで初めてSQLが発行される
  puts user_book.rating
end
2. 柔軟なクエリ構築

クエリを段階的にチェーンで組み立てて、最後にまとめて実行できる

relation = UserBook.where(user: user)
relation = relation.where(rating: 5)
relation = relation.order(created_at: :desc)

relation.to_a # ここで初めてSQLが発行される
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?