LoginSignup
0
2

More than 3 years have passed since last update.

time型で日付またぐ場合も考慮したスコープを追加する

Posted at

やりたいこと

指定した時間内に存在する Hogehogesテーブル) モデルの一覧を取得したい。

カラム名は以下の通りでいずれも time型である

  • 開始時間(start_time
  • 終了時間(end_time

ただし、 end_time < start_time の場合もあり、その場合は日付をまたいでいるとして扱いたい。

やったこと

日付をまたぐ場合も考慮した時間内判定 のロジック持つスコープを用意した。

scope :open_at -> (datetime: Time.current) do
   where("
      CASE WHEN (hoges.start_time <= events.end_time)
      THEN (hoges.start_time <= :time AND :time < hoges.end_time)
      ELSE (:time < hoges.end_time OR hoges.start_time <= :time)
      END",
      time: datetime.to_s(:time))
end
0
2
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
2