现在我有我的 ActionView::Base.field_error_proc
Proc.new do |html_tag, instance|
if html_tag =~ /^<label/ or instance.respond_to?(:object_name)
%{<div class="field_with_errors">#{html_tag}</div>}.html_safe
else
%{<div class="field_with_errors">#{html_tag}<br /><label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
end
当我使用 client_side_validations gem 时,我修改了它以满足我的一些需求。
现在,'fields_with_error' div 环绕着 html_tag(即具体的错误字段)。不过我想知道的是,是否可以修改 div class="fields_with_error"的位置并将其放在包含 error_field 的 div 之后。
例如,
<div class="main_div">
<%= password_field_tag 'secret', 'Your secret here' %>
</div>
然后 div class="fields_with_error"应该定位为
<div class="main_div">
<%= password_field_tag 'secret', 'Your secret here' %>
</div>
<div class="fields_with_error"> <label class="message"> The error message </label> </div>
任何帮助都将非常有值(value)。
最佳答案
所以当我使用 twitter bootstrap 时,我通常会用这样的东西做一个初始化器
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
html = %(<div class="field_with_errors">#{html_tag}</div>).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 = %(<div class="control-group error">#{e}</div>).html_safe
elsif form_fields.include? e.node_name
if instance.error_message.kind_of?(Array)
html = %(<div class="control-group error">#{html_tag}<span class="help-inline"> #{instance.error_message.uniq.join(', ')}</span></div>).html_safe
else
html = %(<div class="control-group error">#{html_tag}<span class="help-inline"> #{instance.error_message}</span></div>).html_safe
end
end
end
html
end
这只是将常规错误调整为表单中的 Twitter 错误 :> 所以一切都非常好看 ;>。您可以使用相同的方法。
如果这有帮助,干杯
关于ruby - 在 Rails 中覆盖 ActionView::Base.field_error_proc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13909393/