我有一个带有 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)
关于ruby-on-rails - Rails : How to query time range, 不是日期,activerecord 中模型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38623069/