Rails验证没有失败

时间:2015-01-12 10:17:04

标签: ruby-on-rails validation proc

我在模型字段上进行了以下验证:

validates :invoice_date, :presence => true, :unless => Proc.new { |invoice| invoice.invoice_date.future? }

它看起来很简单,但它不起作用。如果日期是将来,则不会抛出任何错误。在这种情况下,Proc确实会返回false

知道为什么没有显示任何验证错误?

3 个答案:

答案 0 :(得分:3)

'除非'条件用于决定验证是否应该运行,而不是它应该成功还是失败。因此,您的验证基本上是说“验证invoice_date的存在,除非将来发票_date在此情况下不验证其存在”(这没有任何意义)

听起来你想要两个验证,存在和日期围栏。

validate :invoice_date_in_past

def invoice_date_in_past
  if invoice_date.future?
    errors.add(:invoice_date, 'must be a date in the past')
  end
end

答案 1 :(得分:2)

validates :invoice_date, :presence => true
validate :is_future_invoice_date?

private
 def is_future_invoice_date?
   if invoice_date.future?
     errors.add(:invoice_date, 'Sorry, your invoice date is in future time.')
   end
end

Presence true确保,invoice_date必须存在。 为了验证日期是否是未来日期,我们已经指定了自定义验证方法。(is_future_invoice_date?) 如果日期是将来的日期,此方法将在invoice_date属性中添加错误消息。

此处有更多信息:http://guides.rubyonrails.org/active_record_validations.html#custom-methods

答案 2 :(得分:0)

尝试这样: -

validate check_invoice_date_is_future

def check_invoice_date_is_future
 if invoice_date.present?
   errors.add(:invoice_date, "Should not be in future.") if invoice_date.future?
 else
   errors.add(:invoice_date, "can't be blank.")
 end
end