2013-04-30 109 views
0

我在我的一個Rails模型中有一個簡單的驗證,但它似乎沒有像我想要的那樣觸發一個錯誤。在自定義模型驗證中沒有觸發的錯誤

before_save :check_future_date 

private 
    def check_future_date 
    puts "==============================================================" 
    puts self.article.date 
    puts Date.today 
    if self.article.date <= Date.today 
     puts "error!!!!!!!!!!!!!!!!!"   
     errors[:base] << "Sorry, you must post at least a day in advance" 
    end 
    end 

我知道邏輯被觸發,因爲在控制檯中,我看到:

============================================================== 
2013-04-06 
2013-04-29 
error!!!!!!!!!!!!!!!!! 

然而,成績仍然是保存,並沒有顯示任何錯誤消息。我也嘗試過:

errors.add(:base, 'Sorry, you must post at least a day in advance') 

回答

1

您需要註冊自定義驗證方法,而不是執行before_save

變化

before_save :check_future_date 

validate :check_future_date