ruby-on-rails - Rails Active Record 仅针对 created_at 日期时间值的日期字段进行查询
问题描述
我想从我的“计数”表中返回一些记录。
如何仅获取 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')
推荐阅读
- reactjs - Firebase 实时数据库显示意外行为
- ruby-on-rails - 通过 webpack 将 CKEditor 4 与 Rails 6 集成
- kubernetes - 将离子应用程序部署到 EKS 部署后不加载网站
- javascript - 从 Firestore 获取值时 useState 不更新
- java - 在 CircleCI,当使用多个图像时无法访问 gradle
- r - GGPLOT 标签设计(粗体、间隙)
- hibernate - 如何正确编写查询,以免出现意外的令牌异常?
- flutter - Dart/Flutter - 如何获得自 epoch 以来的第二个:Twitter API 错误代码 135(时间戳超出范围)
- python - mkdir /path: 运行 geth 时出现只读文件系统问题
- r - R:关于使用 lapply() 函数而不是 for 循环的问题