8

我数据库中的日期如下所示:2012-07-23

我正在尝试查看日期是否早于 7 天前且小于 14 天前,或者查看日期是否大于 14 天前,但我没有运气..

这是我的代码:

def progress_report_status_check(date)
    progress_date = date.to_date
    seven_days = 7.days.ago.to_date
    fourteen_days = 14.days.ago.to_date

    if seven_days > (progress_date - 7.days.ago.to_date) or (progress_date - 14.days.ago.to_date) < fourteen_days
      "due"
    elsif (progress_date - 14.days.ago.to_date) > fourteen_days 
      "overdue"
    end 
  end
4

2 回答 2

10
def progress_report_status_check(progress_date) # Pass in a date
  if (progress_date < Date.now-14.days)
    "overdue"
  elsif (progress_date < Date.now-7.days) 
    "due"
  end 
end

或(可读性较差)

def progress_report_status_check(progress_date) # Pass in a date
  (progress_date < Date.now-14.days) ? "overdue" : ((progress_date < Date.now-7.days) ? "due" : "") : "" 
  end 
end

根据您的使用情况,您可能希望创建命名范围,例如:

scope :overdue where(:progress_date < Date.now-14.days)
scope :due where(:progress_date < Date.now-7.days)

然后你的调用代码可以是

def progress_report_status_check(progress_date) # Pass in a date
  self.overdue? ? "overdue" : self.due? ? : "due" : ""
  end 
end
于 2012-08-02T01:59:23.137 回答
6

接受的答案在 Date 类上使用了未定义的方法。这是对的:

def progress_report_status_check(progress_date) # Pass in a date
  if (progress_date < (Date.today-14.days))
    "overdue"
  elsif (progress_date < (Date.today-7.days)) 
    "due"
  end 
end
于 2014-05-24T15:24:16.793 回答