Have you ever spent hours coding up the most awesome form you’ve ever seen only to have Rails break it with it’s error markup? I have, and it really sucks. So today I set out on a mission to solve this ever annoying problem. Here’s how I did it.

Step 1. Find the source.

If you’ve ever gone looking through Rails source, you know this wasn’t a very easy thing to do. But after some digging I found what was causing me so much grief.

# active_record_helper.rb in action_pack/action_view/helpers
@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }

Step 2. Figure out what you want.

I found that the problem was that it was using a div to wrap the incorrect fields. This didn’t work for me. I needed a span so it wouldn’t break the layout. So what do you need? Maybe a div works, but you want to use a different class name? Whatever it is, figure it out. Firebug may be of some help to you.

Step 3. Patch Rails.

I love how easy this step is. Put a file in RAILS_ROOT/config/initializers called rails_ext.rb. You can really name this file whatever you want, but that’s what mine is called.

Next add these lines.

module ActionView
  class Base
    @@field_error_proc = Proc.new{ |html_tag, instance| "<span class=\"fieldWithErrors\">#{html_tag}</span>" }
    cattr_accessor :field_error_proc
  end
end

Now restart your server and enjoy.

Closing Thoughts.

Now I know what you’re thinking. Why don’t I just edit the css? Well here it is. My markup is a big deal. If I want a span I should have a span. I guess it really comes down to preference. Take it or leave it.