如何更改默认的rails错误div“field_with_errors”

我正在使用巫术进行身份validation以及twitter bootstrap 。

我想通过改变添加到DOM的默认rails

来以twitter的bootstrap样式在我的注册表单上设置我的错误消息。

做这样的事情的轨道惯例是什么?

我想你可以添加一些操作DOM的javascript来重命名

,但这看起来像是一个黑客。 似乎应该有一种方法可以在rails中覆盖它,但我无法弄清楚在哪里这样做。

这就是bootstrap要求您标记错误以使用其内置表单错误样式的方式:

 
Please correct the error

从上面的链接,如果您将以下内容放在class Application < Rails::Application of config/application.rb

 config.action_view.field_error_proc = Proc.new { |html_tag, instance| "
#{html_tag}
".html_safe }

validation失败时,您的输入标签将在它们周围有一个红色标记

对于Bootstrap 3.2,你可以使用…… 像这样(将nokogiri gem添加到你的Gemfile中):

 ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| html = %(
#{html_tag}
).html_safe # add nokogiri gem to Gemfile form_fields = [ 'textarea', 'input', 'select' ] elements = Nokogiri::HTML::DocumentFragment.parse(html_tag).css "label, " + form_fields.join(', ') elements.each do |e| if e.node_name.eql? 'label' html = %(
#{e}
).html_safe elsif form_fields.include? e.node_name if instance.error_message.kind_of?(Array) html = %(
#{html_tag} #{instance.error_message.uniq.join(', ')}
).html_safe else html = %(
#{html_tag} #{instance.error_message}
).html_safe end end end html end

将此代码放在config/initializers/field_error_proc.rb文件中(如果不存在则创建一个)

这是稍微修改过的代码: 在Rails中覆盖ActionView :: Base.field_error_proc

在Rails 5上的Twitter Bootstrap 3.3.6,这是一个初始化程序customize_error.rb ,适用于我:

 ActionView::Base.field_error_proc = proc { |html_tag, _instance| "
#{html_tag}
".html_safe }

请注意,如果您使用的是SimpleForm,则在application.rb中使用Proc的接受答案将不起作用。 相反,您应该编辑simple_form初始化程序。 例如使用Bootstrap 3.2:

 config.wrappers :default, class: :input, hint_class: :field_with_hint, error_class: :'has-error' do |b| [...] b.use :hint, wrap_with: { tag: :span, class: :'text-warning' } b.use :error, wrap_with: { tag: :span, class: :'text-danger' } end