Rails:如何在activerecord中查询模型的时间范围,而不是日期
我有一个带time
属性的模型。 它是用户想要收到电子邮件的配置,即美国东部标准时间下午5点。 它以21:00:00
存储在数据库中。 我想按范围查询。 例如,我希望每个用户的提醒时间在20:55:00
到21:05:05
之间。
Rails似乎奇怪地处理时间属性,因为它想要将它显示为完整的DateTime,因此数据库有21:00:00
但是当加载到rails时,它显示为2000-01-01 17:00:00。
我的代码现在看起来像:
scope :receives_report_reminder_at, -> (time) do start = (time - 5.minutes).strftime('%T') ending = (time + 5.minutes).strftime('%T') where(notification_report_reminder_time: start...ending) end
这适用于我的测试用例,但是当我在测试之外尝试时它不起作用。 思考? 有没有一种正确的方法来处理场景,或者我错了吗?
我通过您指定的标签看到您使用的是PostgreSQL数据库。 您可以使用数据库机制将DateTime
类型列转换为time
类型。
这可以通过使用双冒号运算符( ::
:)来完成:
where('notification_report_reminder_time::time >= ? and notification_report_reminder_time <= ?', start, ending)