2016-03-17 32 views
0

我在我的模型內部創建了一個簡單驗證,檢查日期(to_date)是否在當前日期之前。Rails 4的strptime錯誤

用戶提交to_date的格式是%m/%d/%Y或者例如03/15/2016

我的問題是,鐵軌扔我invalid date錯誤,雖然我有三重檢查,日期是在正確的格式。

這裏是我的驗證:

validate :date_not_before_now 

def date_not_before_now 
    if Date.strptime(self.to_date, '%m/%d/%Y').strftime("%Y-%m-%d") < Time.now.localtime.strftime("%Y-%m-%d") 
    errors.add(:dates, "should not be in the past.") 
end 

任何弄清楚爲什麼這不工作,將不勝感激幫助。

回答

0

驗證日期

validates :date_field, presence: true, date: {on_or_before: :today} 

def today 
    Date.today 
end 
+0

感謝您的建議,但on_or_before不會在我的情況下工作,因爲'to_date'是一個字符串 - 而不是日期時間。 – Kathan

0

時,試試這個你可以試試這個。

validate :date_not_before_now 

def date_not_before_now 
    if (Date.strptime(self.to_date, '%m/%d/%Y') < Time.now.localtime.to_date) 
    errors.add(:dates, "should not be in the past.") 
    end 
end 

在控制檯中試過,看到下面的例子。

Date.strptime("03/15/2016", '%m/%d/%Y') < Time.now.localtime.to_date 
## Output 
=> true