【问题标题】:Rails - Query time shiftsRails - 查询时间变化
【发布时间】: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_atend_at的数据类型转换为datetime呢?您可以简单地检查 DateTime.now 是否介于两者之间。

标签: ruby-on-rails ruby postgresql activerecord time


【解决方案1】:

有趣的问题!所以有两种情况:(1)正常班次(start_time &lt;= end_time),(2)与午夜重叠的班次(start_time &gt; end_time)。

您已经通过检查当前时间是否在开始时间和结束时间之间来处理第一种情况。

我相信第二种情况可以通过检查当前时间是或者在开始时间和午夜之间,或者在午夜和结束时间之间来处理。转换为start_time &lt;= ? OR end_time &gt;= ?

我有一段时间没有使用 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()

如果您这样做,请考虑将这两个案例拆分为单独的scopes,这样您就可以在此方法中编写类似这样的更具可读性的内容:

@current ||= current_normal_shifts.or(current_dawn_shifts).first

【讨论】:

    【解决方案2】:

    您可能对tod gem 感兴趣,它提供了一个TimeOfDay 类和一个Shift 类,它采用两个TimeOfDay 对象来表示班次的开始和结束。它按预期处理黎明班次。

    实现可能如下所示:

    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
    

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2016-10-28
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      相关资源
      最近更新 更多