【问题标题】:Retrieve records between hours检索小时之间的记录
【发布时间】:2017-03-03 17:26:01
【问题描述】:

我有以下模型(我正在使用 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 中。

【问题讨论】:

  • 你在使用 mysql 吗?如果是,你介意试试:.where('TIME(pick_up_start_time) &lt;= TIME(?) and TIME(pick_up_end_time) &gt;= TIME(?)', Time.now, Time.now)
  • 我正在使用 postgres

标签: sql ruby-on-rails postgresql activerecord


【解决方案1】:

您可以只使用普通 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)")

【讨论】:

  • 我明白了逻辑,但我不知道为什么它不起作用
  • 不返回预期的结果吗?
【解决方案2】:

我认为这是作用域的完美用例

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

【讨论】:

  • 问题是我不想比较日期,我想比较这些日期中的时间。
  • 它说“时间”列不存在
  • @CarlosGuerrero 抱歉,还有 1 个编辑即将发布
  • 它给出了这个错误 ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: function hour(timestamp without time zone) does not exist
猜你喜欢
  • 1970-01-01
  • 2017-10-01
  • 2019-04-25
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
  • 2018-08-11
  • 1970-01-01
相关资源
最近更新 更多