たまに使う時用のメモ
前提
- ruby 3.2.2 (2023-03-30 revision e51014f9c0) [arm64-darwin21]
- rails (6.1.7.4)
本題
範囲演算子を使おう
# いつ時点以降
Test.where(updated_at: Time.new(2023, 1, 1, 1, 1, 1, 'UTC')..).to_sql
=> "SELECT `tests`.* FROM `tests` WHERE `tests`.`updated_at` >= '2023-01-01 01:01:01'"
# > になると思ったけどならないのか
Test.where(updated_at: Time.new(2023, 1, 1, 1, 1, 1, 'UTC')...).to_sql
=> "SELECT `tests`.* FROM `tests` WHERE `tests`.`updated_at` >= '2023-01-01 01:01:01'"
# いつからいつまで
Test.where(updated_at: Time.new(2023, 1, 1, 1, 1, 1, 'UTC')..Time.new(2023, 1, 1, 1, 1, 1, 'UTC')).to_sql
=> "SELECT `tests`.* FROM `tests` WHERE `tests`.`updated_at` BETWEEN '2023-01-01 01:01:01' AND '2023-01-01 01:01:01'"
# こっちは > になる
Test.where(updated_at: Time.new(2023, 1, 1, 1, 1, 1, 'UTC')...Time.new(2023, 1, 1, 1, 1, 1, 'UTC')).to_sql
=> "SELECT `tests`.* FROM `tests` WHERE `tests`.`updated_at` >= '2023-01-01 01:01:01' AND `tests`.`updated_at` < '2023-01-01 01:01:01'"
# 日付で良い場合は、Date.new(2023, 1, 1)で