自定义 Rails 验证未向输入添加“field_with_errors"包装器 [英] Custom Rails Validation not adding 'field_with_errors' wrapper to inputs
问题描述
我正在使用需要一些自定义验证的表单处理 Rails 4 站点.但是当验证标准失败并显示错误消息时,我正在检查的输入字段没有被赋予 field_with_errors 包装器.正在验证的所有其他字段都正确获取包装器,但它们的验证是对每个属性的简单存在检查.
I'm working on a Rails 4 site with a form that needed some custom validation. But when the validation criteria fails and the error message is shown, the input fields I'm checking aren't given the field_with_errors wrapper. All other fields being validated are getting the wrapper properly, but their validation is a simple presence check on each attribute.
如何在自定义验证中添加包装器?
How can I have the wrapper added in with my custom validation?
附加说明:如果可能的话,我只想显示一次我的错误消息 - 但要突出显示两个字段.
Additional notes: I'd like to only show my error message once, if possible - but highlight both fields.
在我的模型中:
validate :at_least_one_apply_method
def at_least_one_apply_method
if [self.apply_url, self.application_instructions].reject(&:blank?).size == 0
errors[:base] << ("Please provide at least one: Where to Apply or Applications Instructions.")
end
end
让我知道需要的任何其他信息.谢谢!
Let me know of any other information needed. Thank you!
推荐答案
您正在将自定义错误消息添加到 errors[:base].您需要将其添加到要包装的字段中,例如
You are adding the custom error message to errors[:base]. You need to add it to the field which you want to be wrapped e.g.
errors[:apply_url] << ("Please provide at least one: Where to Apply or Applications Instructions.")
errors[: application_instructions] << ("Please provide at least one: Where to Apply or Applications Instructions.")
这篇关于自定义 Rails 验证未向输入添加“field_with_errors"包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!