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

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
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:

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

Comments
Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *