Rails: How to query time range, not date, values for a model in activerecord

霸气de小男生 提交于 2020-01-04 01:57:10

问题


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 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.

My code right now looks like:

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?


回答1:


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)


来源:https://stackoverflow.com/questions/38623069/rails-how-to-query-time-range-not-date-values-for-a-model-in-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!