Rails:如何查询ActiveRecord中模型的时间范围(而非日期)值 [英] Rails: How to query time range, not date, values for a model in activerecord

查看:110
本文介绍了Rails:如何查询ActiveRecord中模型的时间范围(而非日期)值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 time 属性的模型。该配置用于用户希望何时接收电子邮件,即美国东部标准时间下午5点。它以 21:00:00 的形式存储在数据库中。我想按范围查询它。例如,我希望每个用户的提醒时间在 20:55:00 21:05:05 。

I have a model with a time attribute. It's configuration for when a user wants to receive an email, i.e., 5 PM EST. It's stored in the database as 21:00:00. I'd like to query it by range. For example, I'd like every user with a reminder time between 20:55:00 and 21:05:05.

Rails似乎奇怪地处理时间属性,因为它想将其显示为完整的DateTime,因此数据库具有 21:00 :00 ,但将其显示为2000-01-01 17:00:00。

Rails seems to handle time attributes kind of strangely because it wants to show it as a full DateTime, so the database has 21:00:00 but when loaded in rails, it shows it as 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

在我的测试用例中,但是当我在测试之外尝试时不起作用。有什么想法吗?

This works in my test cases but doesn't work when I try it outside of tests. Thoughts? Is there a proper way to handle scenario or am I go about it wrong?

推荐答案

我看到的是您指定的标签,您使用PostgreSQL数据库。您可以使用数据库机制将 DateTime 类型的列转换为 time 类型。

I see by tags, that you specified, that you use PostgreSQL database. You could use a database mechanism to convert DateTime type column to time type.

可以使用双冒号运算符( :: ):

That can be done by using a double colon operator (::):

where('notification_report_reminder_time::time >= ? and notification_report_reminder_time <= ?', start, ending)

这篇关于Rails:如何查询ActiveRecord中模型的时间范围(而非日期)值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆