繁体   English   中英

rails where 在 DateTime 对象上查询当前日期

[英]rails where query for current date on DateTime object

我创建了一个名为:

DoctorAppointment ,主要有两个属性, apt_from: DateTime对象和apt_to: DateTime对象

我为同一天的不同时间创建了多个约会。 我正在尝试获取apt_from:所有约会记录apt_from:具有今天的日期。 以及整个星期

这似乎不起作用。

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

这似乎没有返回任何记录,即使我在当前日期创建了一些记录。

我在这里做错了什么?

更新:由于 sql 关键字冲突,我解决了我面临的问题之一。 看到评论后。

我正在使用 Rails 6 和 sqlite

您正在将DateTimeDateTime进行比较,它们是不同的,因此您没有得到任何结果。 要查找今天的约会,您只需要检查Date而不是DateTime

试试sqlite的strftime函数

查找今天的约会

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

尝试这个

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

这将返回今天的所有记录

由于时区的原因,在比较 SQL 和 Ruby 之间的日期时必须小心。 我发现使用Time.current更安全,因为该方法是时区感知的。

你可以这样做... 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.

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