Rails 仅针对 created_at 日期时间值的日期字段的 Active Record 查询
Rails Active Record query against just the date field of the created_at datetime value
我想 return 我的 "counts" table 中的一些记录。
如何只获取 created_at 字段的日期部分,如下所示使用 date(created_at) 不起作用。
Count.where(channel_id: channel_id)
.where(date(created_at:) :date Date.yesterday)
.followers
感谢您的指导。
西蒙
一个简单的技巧是使用 BETWEEN
子句,无需编写纯 SQL 即可实现,只需使用 ActiveRecord:
Count
.where(channel_id: channel_id)
.where(created_at: Date.yesterday.beginning_of_day..Date.yesterday.end_of_day)
它将翻译成以下内容SQL:
WHERE ("counts"."created_at" BETWEEN '2019-01-02 00:00:00.000000' AND '2019-01-02 23:59:59.999999')
我想 return 我的 "counts" table 中的一些记录。
如何只获取 created_at 字段的日期部分,如下所示使用 date(created_at) 不起作用。
Count.where(channel_id: channel_id)
.where(date(created_at:) :date Date.yesterday)
.followers
感谢您的指导。
西蒙
一个简单的技巧是使用 BETWEEN
子句,无需编写纯 SQL 即可实现,只需使用 ActiveRecord:
Count
.where(channel_id: channel_id)
.where(created_at: Date.yesterday.beginning_of_day..Date.yesterday.end_of_day)
它将翻译成以下内容SQL:
WHERE ("counts"."created_at" BETWEEN '2019-01-02 00:00:00.000000' AND '2019-01-02 23:59:59.999999')