我对模型字段进行了以下验证:
validates :invoice_date, :presence => true, :unless => Proc.new { |invoice| invoice.invoice_date.future? }
它看起来很简单,但它不起作用。如果日期是将来的日期,则不会引发错误。在这种情况下,Proc
确实会返回false
。
知道为什么没有显示任何验证错误吗?
"除非"条件用于决定是否应该运行验证,而不是它应该成功还是失败。所以你的验证本质上是说"验证invoice_date的存在,除非invoice_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
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
临在真只是确保,invoice_date必须存在。为了验证日期是否是将来的日期,我们指定了一个自定义验证方法。(is_future_invoice_date?如果日期是将来的日期,此方法将针对我们的 invoice_date 属性添加错误消息。
更多信息在这里: http://guides.rubyonrails.org/active_record_validations.html#custom-methods
像这样尝试:--
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