Applying different error display styles

July 11, 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:

def with_error_proc(error_proc)
  pre = ActionView::Base.field_error_proc
  ActionView::Base.field_error_proc = error_proc
  ActionView::Base.field_error_proc = pre

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

ERROR_PROCS[:errors_below] = do |html_tag, instance|
  html_tag+' error'
  # renders errors below the field

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


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...

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...

SpringOne 2021

Register Now