【发布时间】:2018-10-09 11:06:09
【问题描述】:
目前我正在开发一个管理轮班的系统。
系统包含一个端点,该端点根据服务器时间返回当前班次。我创建了一个查询,该查询适用于 08:00 AM 到 04:00 PM 等常规班次,但挑战是从前一天晚上 10:00 开始到 06:00 AM 的黎明班次。
我的模型包含以下字段:
- 名称(字符串)
- start_at(时间)
- end_at(时间)
Ps.:我使用 Postgres 作为数据库。
我的代码:
class Shift < ApplicationRecord
def self.current
current_time = Time.now()
current_time = current_time.change(year: 2000, month: 1, day: 1)
@current ||= Shift
.where('start_time <= ?', current_time)
.where('end_time >= ?', current_time)
.first()
end
end
Ps.:我想,由于我在数据库中使用 Time 类型,我必须规范化 Time.now 以使用 2000 - 01 - 01 日期。
那么,有没有一种简单/最好的方法来做到这一点?
感谢您的帮助!
【问题讨论】:
-
不知道它是否适合你,但为什么不将
start_at和end_at的数据类型转换为datetime呢?您可以简单地检查 DateTime.now 是否介于两者之间。
标签: ruby-on-rails ruby postgresql activerecord time