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?

More than 1 year has passed since last update.

ActiveRecord 日付・時刻検索メモ

Posted at

たまに使う時用のメモ

前提

  • 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)で

参考

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?