[英]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 DoctorAppointment
,主要有两个属性, apt_from: DateTime
对象和apt_to: DateTime
对象
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.我正在尝试获取
apt_from:
所有约会记录apt_from:
具有今天的日期。 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.更新:由于 sql 关键字冲突,我解决了我面临的问题之一。 After seeing the comment.
看到评论后。
I am using Rails 6 and sqlite我正在使用 Rails 6 和 sqlite
You are comparing DateTime
with DateTime
which are different hence you are not getting any results.您正在将
DateTime
与DateTime
进行比较,它们是不同的,因此您没有得到任何结果。 To find Today's appointment you just need to check the Date
& not DateTime
要查找今天的约会,您只需要检查
Date
而不是DateTime
Try strftime function of sqlite试试sqlite的strftime函数
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.由于时区的原因,在比较 SQL 和 Ruby 之间的日期时必须小心。 I find it is safer to use
Time.current
because that method is timezone-aware.我发现使用
Time.current
更安全,因为该方法是时区感知的。
You could do this... all_day
is a special Rails method which returns the range你可以这样做...
all_day
是一个特殊的 Rails 方法,它返回范围
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.