mattmcmanus mattmcmanus - 4 months ago 11
Ruby Question

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

I have a model with a

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
. I'd like to query it by range. For example, I'd like every user with a reminder time between

Rails seems to handle time attributes kind of strangely because it wants to show it as a full DateTime, so the database has
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)

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?


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)