Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

  • Blog Navigation
Applying different error display styles

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.

Share This