Applying different error display styles

July 12, 2007 Pivotal Labs

Rails’ build-in view helpers (text_field, etc.) can automatically render errors. The default error display is easy to use and functional, but it only goes so far. Sometimes, it’s necessary to display errors in different ways in different parts of your application.

Rails provides a way of changing error rendering in “ActionView::Base.field_error_proc”. Unfortunately, the only way to change the error display is on a global basis, which makes the following code non-thread safe.

We wanted to apply different error styles to different views. A simple helper method, such as this one, will allow you to specify the error display you would like to use:

<code>
def with_error_proc(error_proc)
  pre = ActionView::Base.field_error_proc
  ActionView::Base.field_error_proc = error_proc
  yield
  ActionView::Base.field_error_proc = pre
end
</code>

To define different error display styles, we can use a hash that contains various error procs:

<code>
ERROR_PROCS = {}
ERROR_PROCS[:errors_below] = Proc.new do |html_tag, instance|
  html_tag+' error'
  # renders errors below the field
end
</code>

Finally, to use this in your controller, just wrap the render method with #with_error_proc. It’s also possible to use this directly in your view.

About the Author

Biography

Previous
The Controller Formula
The Controller Formula

When I introduce a programmer to Rails I encourage them to read the article Skinny Controller, Fat Model. M...

Next
Taming JavaScript in practice: AJAX with Protoype
Taming JavaScript in practice: AJAX with Protoype

In a previous post I discussed how to unit-test client-side AJAX JavaScript code using JsUnit. In that pos...