Ruby on rails Rails-查询时移
目前我正在开发一个管理轮班的系统 系统包含一个端点,该端点根据服务器时间返回当前班次。我创建了一个查询,它适用于常规轮班,如上午8:00到下午4:00等等,但挑战在于,从前一天起,每天早上10:00到早上6:00之间都有一个早班 我的模型包含以下字段:Ruby on rails Rails-查询时移,ruby-on-rails,ruby,postgresql,activerecord,time,Ruby On Rails,Ruby,Postgresql,Activerecord,Time,目前我正在开发一个管理轮班的系统 系统包含一个端点,该端点根据服务器时间返回当前班次。我创建了一个查询,它适用于常规轮班,如上午8:00到下午4:00等等,但挑战在于,从前一天起,每天早上10:00到早上6:00之间都有一个早班 我的模型包含以下字段: 名称(字符串) 在(时间)开始 在(时间)结束 附言:我正在使用Postgres作为数据库 我的代码: class Shift < ApplicationRecord def self.current current_tim
- 名称(字符串)
- 在(时间)开始
- 在(时间)结束
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
班次
注:我想,因为我在数据库中使用时间类型,我必须规范化时间。现在使用2000-01-01日期
那么,有没有一种简单/最好的方法可以做到这一点
谢谢你的帮助 有趣的问题!所以有两种情况:(1)正常移位(其中
开始时间结束时间)
通过检查当前时间是否在开始时间和结束时间之间,您已经在处理第一个案例
我相信第二种情况可以通过检查当前时间是在开始时间和午夜之间,还是在午夜和结束时间之间来处理。这转换为开始时间=?
我已经有一段时间没有使用Rails了,但我认为您可以这样做:
@current ||= Shift
.where('start_time <= end_time')
.where('start_time <= ?', current_time)
.where('end_time >= ?', current_time)
.or(Shift
.where('start_time > end_time')
.or(Shift
.where('start_time <= ?', current_time)
.where('end_time >= ?', current_time)))
.first()
require 'tod'
class Shift < ApplicationRecord
def self.current
find(&:current?)
end
def current?
schedule.include?(Tod::TimeOfDay(Time.now))
end
def schedule
Tod::Shift.new(Tod::TimeOfDay(start_time), Tod::TimeOfDay(end_time))
end
end
您可能对提供TimeOfDay
类和Shift
类的感兴趣,该类使用两个TimeOfDay
对象来表示班次的开始和结束。它能按预期处理黎明换班
实现可能如下所示:
@current ||= Shift
.where('start_time <= end_time')
.where('start_time <= ?', current_time)
.where('end_time >= ?', current_time)
.or(Shift
.where('start_time > end_time')
.or(Shift
.where('start_time <= ?', current_time)
.where('end_time >= ?', current_time)))
.first()
require 'tod'
class Shift < ApplicationRecord
def self.current
find(&:current?)
end
def current?
schedule.include?(Tod::TimeOfDay(Time.now))
end
def schedule
Tod::Shift.new(Tod::TimeOfDay(start_time), Tod::TimeOfDay(end_time))
end
end
需要“tod”
班次<应用记录
def自电流
查找(&:当前?)
结束
def电流?
计划。包括?(Tod::TimeOfDay(Time.now))
结束
def时间表
Tod::Shift.new(Tod::TimeOfDay(开始时间),Tod::TimeOfDay(结束时间))
结束
结束
不知道它是否适合您,但为什么不将start\u at
和end\u at
的数据类型转换为datetime
?您只需检查DateTime.now是否介于两者之间。