Abi*_*bid 0 validation ruby-on-rails ruby-on-rails-3
我有一个包含大量字段的大型表单,我们在rails中获取错误的方法是将它们驻留在模型对象内。我想要一种干净的方法来显示每个字段以外的错误,而不是分别显示。有没有可以做到这一点的宝石,如果现在可以做到这一点的最佳方法是什么?
我希望每个错误除显示错误所在的字段外显示。
假设您正在使用Rails 3+和Rails Form Helper,则不需要任何gem,也不需要遍历错误收集。
好吧,这并非完全正确,但Rails会为您做到。您只需要提供一个proc。
我将以下内容添加到... / config / application.rb中:
# wrap each form field that has an error with the following.
# note, condition for arrays and singletons.
config.action_view.field_error_proc = Proc.new do |html_tag, instance|
if instance.error_message.kind_of?(Array)
%(<span class="validation-error">#{html_tag}</span>).html_safe
else
%(#{html_tag}<span class="validation-error"> </span>).html_safe
end
end
Run Code Online (Sandbox Code Playgroud)
确保定义CSS类验证错误。这样就可以使其正常工作,然后可以对其进行调整以满足您的需求。注意,您的CSS可以特定于每种字段类型,例如输入,文本区域,选择等。
当然还要重新启动Rails应用程序。
我实际上是在SO的另一个线程中学到的,但是现在找不到,因此无法提供参考。