[英]Rails convert DateTime to date in 'where' query
我需要對數據庫進行查詢並按開始日期過濾事件,但列類型是DateTime。 我在模型中做了范圍:
scope :day, -> (start_date) {where start_date: start_date}
它適用於相同的DateTime值,但我需要一個過濾器來僅按日期獲取Event
,而不是DateTime。
我有PG數據庫並嘗試:
scope :day, -> (start_date) {where("start_date:date =?", "#{start_date.to_date}")}
但是我收到了一個錯誤
如果要將數據庫值強制轉換為日期,則必須為不同的數據庫服務器執行不同的操作,例如mysql的以下內容:
scope :day, -> (start_date) {where("DATE(start_date) = ?", start_date)}
因此,將start_date參數強制轉換為日期時間可能更為合理:
scope :day, -> (start_date) {where start_date: start_date.to_datetime}
此外,BigRon在開始和結束之間發布了一個很好的過濾方法,Deep 發布了Rails 5.1的幫助程序,進一步簡化了這種方法,但如果你想按日期過濾,你真的應該考慮你的數據庫列是否真的需要是datetime單獨。
你可以這樣做:
使用SQL Date函數(取決於數據庫,這是用於MySQL
):
scope :on_day -> (start_date) { where("DATE(start_date) = ?", start_date.to_date) }
或者使用范圍(所以這將使用日期和時間來檢查,只使用當天的開始和結束時間並執行BETWEEN
查詢):
scope :day, -> (start_date) { where start_date: start_date.beginning_of_day..start_date.end_of_day }
或者如果在Rails 5.1上 (這是Rails 5.1中引入的新助手):
scope :day, -> (start_date) { where start_date: start_date.all_day }
您可以在一天的開頭到一天結束時使用范圍:
scope :day, -> (start_date) {where start_date: start_date.beginning_of_day..start_date.end_of_day}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.