mattmcmanus
mattmcmanus

Reputation: 1796

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

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?

Upvotes: 3

Views: 1909

Answers (1)

maicher
maicher

Reputation: 2745

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)

Upvotes: 3

Related Questions