and*_*ndi 6 validation ruby-on-rails actionview field-with-errors
不能获得<div class="fieldWithErrors">包含验证错误的包装的arround选择标记是否正常?我个人认为没有理由为什么选择标签应该与其他表格标签(输入,textarea)区别对待.
我确实得到了该字段的错误error_messages_for和error_message_on方法.
PS.我已经改变了一点ActionView::Base.field_error_proc,以获得span标签而不是div,但这不是问题.
ActionView::Base.field_error_proc = Proc.new { |html_tag, instance|
#if I puts html_tag here I only get the <input> tags
"<span class=\"fieldWithErrors\">#{html_tag}</span>"
}
Run Code Online (Sandbox Code Playgroud)
因为我无法找出为什么 select 标签没有包含在该 Proc 中,所以我创建了一个辅助方法,它的作用几乎相同。
def field_with_error(object, method, &block)
if block_given?
if error_message_on(object, method).empty?
concat capture(&block)
else
concat '<span class="fieldWithErrors">' + capture(&block) + '</span>'
end
end
end
Run Code Online (Sandbox Code Playgroud)
我在我的观点中使用它,如下所示:
<% field_with_error @some_object, :assoc do %>
<%= f.select(:assoc_id, @associations.collect {|assoc| [ asoc.name, assoc.id ] }) %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
如果有人知道更好或更干净的方法,我愿意接受建议。