错误未在自定义模型验证中触发

时间:2013-04-30 01:32:32

标签: ruby-on-rails ruby

我在我的一个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 个答案:

答案 0 :(得分:1)

您需要注册自定义验证方法,而不是执行before_save

更改

before_save :check_future_date

validate :check_future_date