2017-03-03 77 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

它说列“时间”不存在 –