简体   繁体   中英

rails where query for current date on DateTime object

I have created a model called:

DoctorAppointment , which has mainly two attributes, apt_from: DateTime object and apt_to: DateTime object

I have created multiples appointments for different times for the same day. And I am trying get all the appointment records for apt_from: having today's date. and for the whole week

This doesnt seem to work.

DoctorAppointment.where("apt_from =?" ,DateTime.now)

This doesnt seem to return any records, even though I created some records on the current date.

What am I doing wrong here?

UPDATE: I fixed one of the issues I was facing, because of the sql keyword conflict. After seeing the comment.

I am using Rails 6 and sqlite

You are comparing DateTime with DateTime which are different hence you are not getting any results. To find Today's appointment you just need to check the Date & not DateTime

Try strftime function of sqlite

To find Today's appointment

DoctorAppointment.where("STRFTIME('%Y-%m-%d', apt_from) = ?", Date.today)

Try this

DoctorAppointment.where("apt_from > ? AND apt_from < ?", DateTime.now.beginning_of_day, DateTime.now.end_of_day)

This will return all the records for today

You have to be careful when comparing dates between SQL and Ruby, because of time zones. I find it is safer to use Time.current because that method is timezone-aware.

You could do this... all_day is a special Rails method which returns the range

Time.current
-> Wed, 09 Sep 2020 00:00:00 UTC +00:00..Wed, 09 Sep 2020 23:59:59 UTC +00:00


DoctorAppointment.where(apt_from: Time.current.all_day)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM