首页 > 解决方案 > Rails Active Record 仅针对 created_at 日期时间值的日期字段进行查询

问题描述

我想从我的“计数”表中返回一些记录。

如何仅获取 created_at 字段的日期部分,使用如下 date(created_at) 不起作用。

Count.where(channel_id: channel_id)
     .where(date(created_at:) :date Date.yesterday)
     .followers

感谢您的任何指导。

西蒙

标签: ruby-on-railsrails-activerecord

解决方案


一个简单的技巧是使用一个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')

推荐阅读