Rails request between two

I have a rails application that has a Checkin model. I want to find all records that are within a specific time range for the current day. How to write where to get all records created between 12:00 and 16:30?

+7
source share
3 answers

@ x1a4 the answer should be good for you, but you can do it in a more understandable and shorter way using 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") any other way to create time.

+36
source

It seems like this will work, assuming the UTC time zone:

 Record.where('created_at > ? AND created_at < ?', Date.today + 12.hours, Date.today + 16.5.hours) 

or using BETWEEN :

 Record.where('created_at BETWEEN ? AND ?', Date.today + 12.hours, Date.today + 16.5.hours) 

BETWEEN may or may not include a second value in the range. Postgres includes it .

+8
source

You can use the bottom stone to search for entries between dates,

This gem is pretty easy to use and more understandable [By star] [1]. I use this gem and the API is more understandable and the documentation is also well explained.

 Post.between_times( Time.zone.now - 3.hours, # all posts in last 3 hours Time.zone.now ) 

Here you can also pass our field Post.by_month("January", field: :updated_at)

Please review the documentation and try.

0
source

All Articles