« Selenium Hackfest | Main | well done software sales »

Rails View Error Handling

I am writing a few apps right now in rails. Actually, i am converting some apps from Mason to Rails to see how it goes.

One thing that i want to change right away is the big red summarized set of error message when a form has trouble.

Searching through the rails wiki turns up an example of customizing the display of an individual field that has an error (with the caveat that it doesn't work on fields hooked up to foreign keys in the model). This requires redefining a helper method stored in a class variable. The redefinition looks like this:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
      msg = instance.error_message
      title = msg.kind_of?(Array) ? '* ' + msg.join("\n*") : msg
          "<div class=\"fieldWithErrors\" title=\"#{title}\">Please fill in this field: #{html_tag}</div>"

To be able to display my own error message summary, i need to do the following:

class ActionView::Base
    def error_messages_for(object_name, options = {})
        options = options.symbolize_keys
        object = instance_variable_get("@#{object_name}")
        unless object.errors.empty?
            content_tag("p", "Bah!  There were errors!")

While this is simple, it is a weird option. At the snakes and rubies, David spoke about what was "above the cut" for rails. To David, an rss generator is above the cut. Apparently, requiring users to redefine internals to change the display of error messages is not above the cut.

What seems simpler is to provide a place for your controller or application view to define templates for error messages and an optional method to transform object.errors on its way into this template. At least leaving display logic in the views/ tree would give people most of what they need in the place that they would look for it first. Now, i know that ActionPack is a pretty tightly coupled controller + view combination, but this still seems clunky.

I didn't find a lot of good info online for this need, so if anyone knows of any examples that i can look at, i would appreciate the links. Also, if anyone knows a simpler way that i can get these things done, please let me know.