Fixing div.fieldWithErrors in Ruby on Rails
Saturday, May 5th, 2007Rails’ form helpers are incredibly handy in quickly writing form code, however their error handling code leaves something to be desired. By default, when a field has errors associated with it, the input is wrapped in a div of class “fieldWithErrors”. Unfortunately, this behavior requires you to explicitly change the div to display inline so it doesn’t make the input appear on the next line after the name of the field. I have also had some trouble getting this setting to work in Safari, although that may just be my problem and not Safari’s.
Fortunately, fixing this annoying little gotcha is as easy as adding a single line to the end of your environment.rb file: (I’ve split it into two lines so it will fit on the page, just remove the line break)
ActionView::Base.field_error_proc = Proc.new { |html_tag, instance|
"<span class=\"fieldWithErrors\">#{html_tag}</span>" }
I know many people have already written about this problem, but I wanted to have my own record of it for easy reference 😉