我想找到一种方法来自定义默认错误html
<div class="field_with_errors"></div>
参加我自己的课程:
<div class="clearfix error">
<label for="errorInput">Input with error</label>
<div class="input">
<input class="xlarge error" id="errorInput" name="errorInput" size="30" type="text">
<span class="help-inline">Small snippet of help text</span>
</div>
</div>
我相信从2007年开始使用Rails 2的这个railscast。 http://railscasts.com/episodes/39-customize-field-error。看起来Rails 3可能有更友好的方式来自定义这个HTML?
此外,它没有显示将错误类直接添加到输入中的方法,就像我想要的那样。
答案 0 :(得分:7)
您发布的链接中说明的方法今天仍在使用vanilla form builders in Rails。
所以,如果你想像你提到的那样包装你的输入,请创建一个覆盖ActionView::Base.field_error_proc
文件中environment.rb
的方法,例如:
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if instance.error_message.kind_of?(Array)
%(<div class="form-field error">#{html_tag}<small class="error">
#{instance.error_message.join(',')}</small></div).html_safe
else
%(<div class="form-field error">#{html_tag}<small class="error">
#{instance.error_message}</small></div).html_safe
end
end
在上面的代码中,我将输入(#{html_tag})包含在<div class="form-field error>..</div>
中ZURB Foundation默认使用的<small class="error">...</small
。我还使用{{1}}标签(也是默认的基础)来显示输入下方的消息。
但是,我建议使用像simple_form这样的表单构建器gem。它可以清理您的视图代码,并允许您需要的自定义级别。
查看其上的railscast here。
祝你好运!