views:

198

answers:

2

Hi I would like to understand how are the error messages displayed in ruby on rails, more importantly how is the order determined in which the error messages are displayed on the page.

Thanks for your time.

+1  A: 

Active Record offers many pre-defined validation helpers. Every time a validation fails, an error message is added to the object’s errors collection, and this message is associated with the field being validated. See this excellent guide for more details on validation.

I believe that since the validation targets are stored in a hash, their order is never guaranteed. But there are many existing plugins to customize and enhanced the default validation. A quick search yields CleverValidation and CustomErrorMessage...

You might be interested in this blog post as well, which talks on how to customize the validation yourself.

JRL
Someone can write an excellent plugin which will display the errors in an order. I do find it weird that no one else has this issue/side effect.
iHeartDucks
The article looks very helpful. Thanks.
iHeartDucks
A: 

Most common way to display errors is to use helper error_messages:

<%= f.error_messages %>

As far as I know it adds some html tags to error messages that are stored in @my_object.errors hash. Error messages are ordered hash and they are in order that your validations are specified in model (at least it works like this in my applications). You can read more about Errors class here.

Since error_messages are just a helper, you can write your own helper to display error messages.

klew
Interestingly, it does not work for me that way. The order of the error messages are in a random order, when compared to the order in the model.
iHeartDucks
Maybe it is related to ruby version. For sure OrderedHash is in ruby 1.9, but I'm working on 1.8.7 and in Rails it is and is working. Try in console on any ActiveRecord object `some_object.errors`. Does it give you `@errors=#<OrderedHash {}>` at the end of print?
klew
no, it does not.
iHeartDucks
What version of ruby and RoR are you using?
klew
I was using ruby 1.8.7 and rails 2.3.4. I just upgraded to 2.3.5 and now the error messages are displayed in the order in which they were declared in the model. phew... this one drove me crazy. Thanks for your help :-)
iHeartDucks
You're welcome :)
klew