在轨道上查找并计算ruby中的连续记录

时间:2013-07-11 23:03:25

标签: ruby-on-rails-3 postgresql-9.1

我有一个跟踪员工时间的应用。员工每12天至少休息2天......员工应该为day_off输入布尔值为true的记录...但是,如果他们不这样做,我也想在几天内找到休息日关闭。我试图简单地计算日期减少一天的记录,从布尔day_off开始或在连续日期中断...并在给定日期结束。

这是我正在处理的帮手

  def consecutive_days_on(user, dutylog)
    # dutylog will be supplied via a loop

    last_day_off = user.dutylogs.where("entry_date < ?", dutylog.entry_date).where(day_off: true).last
    start_date = dutylog.entry_date

      if last_day_off.present?
        end_date = last_day_off.entry_date
        # if the user logged their days off
      else
        end_date = user.dutylogs.where("entry_date < ?", dutylog.entry_date).last.entry_date
        # as of now this just finds the last record...it needs to iterate and increment date to find a break in days on
        # to find break in consecutive dates...if user did not log days off
      end

      user.dutylogs.where("entry_date >= ? AND entry_date <= ?", start_date, end_date).count
      # count the records between the two dates...to find consecutive days on
  end

1 个答案:

答案 0 :(得分:0)

我重构了我的帮助......它有效。我决定依赖用户在他们的日志中输入一天作为关闭...而不是假设输入日期中断可以被视为休息日。

   def consecutive_days_on(user, dutylog)
     last_day_off = user.dutylogs.where(day_off: true).where("entry_date < ?", dutylog.entry_date).select(:entry_date).last
     start_date = dutylog.entry_date

      if last_day_off.present?
        end_date = last_day_off.entry_date
      else
        end_date = dutylog.entry_date
      end

      a = user.dutylogs.where("entry_date >= ? AND entry_date <= ?", end_date, start_date).count
      a-1
   end