2017-03-03 86 views
0

我有以下的模型(我使用Ruby on Rails的):檢索小時記錄

# MealSetting model 
    # week_day:integer 
    # pick_up_start_time:datetime 
    # pick_up_end_time:datetime 

我想檢索所有那些在一定時間內提供的飯菜,飯後可如果pick_up_start_time <= current_hourpick_up_end_time >= current_hour

pick_up_start_time:datetimepick_up_end_time:datetime實際上是日期,但我只使用小時。

我有這個疑問,

MealSetting 
    .where('pick_up_start_time::time <= ? and pick_up_end_time::time >= ?', 
    Time.now.utc.strftime("%T"), 
    Time.now.utc.strftime("%T")) 

但它不工作,因爲在數據庫中的日期將被存儲在UTC。

+0

,你會介意與嘗試:?'。凡(「TIME(pick_up_start_time)<= TIME (?)和TIME(pick_up_end_time)> = TIME(?)',Time.now,Time.now)' – fanta

+0

我正在使用postgres –

回答

0

您可以使用普通SQL並使用now()方法。 由於您想比較日期內的小時數,您可以使用postgres的date_part函數。

MealSetting.where("date_part('hour', NOW()) BETWEEN date_part('hour', pick_up_start_time) AND date_part('hour', pick_up_end_time)") 
+0

我得到邏輯,但我不知道爲什麼它不起作用 –

+0

它不會返回預期的結果嗎? – Iceman

+0

不,它沒有。 –

0

我認爲這是一個完美的使用情況,你使用MySQL,如果是這樣範圍

class MealSettings < ApplicationRecord 

    scope :ready_for_pickup, -> { where("hour(pick_up_start_time) <= ?", Time.now.utc.hour) } 
    scope :before_pickup_ends, -> { where("hour(pick_up_end_time) >= ?", Time.now.utc.hour) } 

end 

MealSettings.ready_for_pickup.before_pickup_ends 
+0

問題是我不想比較我想在這些日期內比較de小時的日期。 –

+0

好吧,讓我編輯它 – Sean

+0

它說列「時間」不存在 –