[英]rails where query for current date on DateTime object
我創建了一個名為:
DoctorAppointment
,主要有兩個屬性, apt_from: DateTime
對象和apt_to: DateTime
對象
我為同一天的不同時間創建了多個約會。 我正在嘗試獲取apt_from:
所有約會記錄apt_from:
具有今天的日期。 以及整個星期
這似乎不起作用。
DoctorAppointment.where("apt_from =?" ,DateTime.now)
這似乎沒有返回任何記錄,即使我在當前日期創建了一些記錄。
我在這里做錯了什么?
更新:由於 sql 關鍵字沖突,我解決了我面臨的問題之一。 看到評論后。
我正在使用 Rails 6 和 sqlite
您正在將DateTime
與DateTime
進行比較,它們是不同的,因此您沒有得到任何結果。 要查找今天的約會,您只需要檢查Date
而不是DateTime
試試sqlite的strftime函數
查找今天的約會
DoctorAppointment.where("STRFTIME('%Y-%m-%d', apt_from) = ?", Date.today)
嘗試這個
DoctorAppointment.where("apt_from > ? AND apt_from < ?", DateTime.now.beginning_of_day, DateTime.now.end_of_day)
這將返回今天的所有記錄
由於時區的原因,在比較 SQL 和 Ruby 之間的日期時必須小心。 我發現使用Time.current
更安全,因為該方法是時區感知的。
你可以這樣做... all_day
是一個特殊的 Rails 方法,它返回范圍
Time.current
-> Wed, 09 Sep 2020 00:00:00 UTC +00:00..Wed, 09 Sep 2020 23:59:59 UTC +00:00
DoctorAppointment.where(apt_from: Time.current.all_day)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.