Kyle Decot Kyle Decot - 6 days ago 4
Ruby Question

Rails query between two times

I have a rails app that has a

Checkin
model. I want to find all records that are within a specific time range for the current day. How would I write a
where
to get all records that were created between 12PM and 4:30PM?

Answer

@x1a4's answer should be good for you but you can do it in a more readable and shorter way, using a range.

 Chekin.where(created_at: Time.parse("12pm")..Time.parse("4:30pm"))

It should generate something like:

SELECT "checkins".*
FROM "checkins" 
WHERE ("checkins"."created_at" BETWEEN '2012-05-28 12:00:00.000000' AND '2012-05-28 16:30:00.000000')

You can change Time.parse("12pm") with any other way to create a time.