Rails 验证没有失败
Rails validation not failing
我对模型字段进行了以下验证:
validates :invoice_date, :presence => true, :unless => Proc.new { |invoice| invoice.invoice_date.future? }
看起来很简单,但是行不通。如果日期在未来,则不会抛出错误。在那种情况下 Proc
确实 returns false
。
知道为什么没有显示任何验证错误吗?
像那样尝试:--
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
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
'unless' 条件用于决定验证是否应该 运行 ,而不是决定是否应该成功或失败。所以你的验证本质上是说 "validate the presence of invoice_date, unless invoice_date is in the future in which case don't validate its presence" (这没有意义)
听起来你想要两个验证,存在和日期隔离。
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, :unless => Proc.new { |invoice| invoice.invoice_date.future? }
看起来很简单,但是行不通。如果日期在未来,则不会抛出错误。在那种情况下 Proc
确实 returns false
。
知道为什么没有显示任何验证错误吗?
像那样尝试:--
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
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
'unless' 条件用于决定验证是否应该 运行 ,而不是决定是否应该成功或失败。所以你的验证本质上是说 "validate the presence of invoice_date, unless invoice_date is in the future in which case don't validate its presence" (这没有意义)
听起来你想要两个验证,存在和日期隔离。
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