ruby检查当前日期是否在日期记录内

时间:2014-08-28 13:05:12

标签: ruby-on-rails ruby

假设我有一个名为Absence的模型,看起来像这样

         :id => :integer,
:employee_id => :integer,
 :start_date => :date,
   :end_date => :date

我需要检查一个员工今天是否离开,如果他们是,则返回true。如果有缺席记录,有人就会离开

  1. 开始日期是今天或今天之前,
  2. 结束日期为null,或今天或今天之前。
  3. 所以我在Employee上需要一个类似

    的方法
    def is_away
      ?????
    end
    

    请帮忙!

3 个答案:

答案 0 :(得分:2)

我会做这样的事情:

# add this to absence.rb
def covers_today?
  (start_date..end_date).cover?(Date.today)
end

# add this to employee.rb
def away?
  absences.any?(&:covers_today?)
end

执行此操作后,只需拨打away?上的employee

@employee.away? 
# => true, if employee has an absense that covers the current date

答案 1 :(得分:2)

假设Employee has_many :absences,这应该有效:

def away?(date = Date.today)
  absences.where('start_date <= :date AND (end_date >= :date OR end_date IS NULL)', date: date).exists?
end

答案 2 :(得分:0)

你也可以尝试一下。

def is_away?
  (start_date <= Date.today) and (end_date.nil? or end_date <= Date.today) ? true : false
end