Custom error messages in validations - Rails3 - Part#2 The Long Answer
21 Feb 2011In a previous post I showed how to get customized error messages in Rails3. Here I'm gonna break it down in case the that wasn't clear enough.
The use of gems
First, I'd like to point out that there are some gems for this kind of job, here they are:
https://github.com/gumayunov/custom-err-msg
https://github.com/markcatley/advanced_errors
BUT I think something so trivial like this was not supposed to need extra libraries to get donne. That's why I exclude the use of such gems as an option. The less dependencies, the better.
The "add_to_base" way
This is another way to get this job donne, but this method (described here in details) has a few disadvantages.
- This method is used to set a general error message to the object it self, not to any particular attribute. That's why the name of the attribute won't show up. But it just doesn't make sense. See, if it is used for messaging about the "name" attribute, it needs to be "attached" to "name", right? That's the way Rails works.
- Doing this you'r gonna need to rewrite the validation methods. I don't like to rewrite things. If you'd like to "validate_uniqueness_of" some attribute, you would have to write a method to do that. Can you picture this?
Doing it right (I suppose)
If you take a look at the view you scaffolded, you will see somthing like:
1
@instance.errors.full_messages
where full_mesages is a method defined in ActiveModel::Errors. It basically gets the message you specified in the model and prepend it with the attribute name. It does that for each attribute that failed validations, and returns them as an array.
Use Rails console, and take a look at the output of @instance.errors (of course, create a new instance with nil values in its attributes and try to save it, before). It should return a hash, were the attribute is the key, and the message is the value. The code shown in the previous post loops trough the hash, returning just the messages!
That how we achieve this without extra libraries, without having to rewrite validations, and makes perfect sense to the framework. And of course, if you found a better way, let me now!
Links mentioned in this text:
https://github.com/gumayunov/custom-err-msg
https://github.com/markcatley/advanced_errors
http://lindsaar.net/2008/4/22/tip-14-custom-error-messages-in-validations
https://github.com/rails/rails/blob/master/activemodel/lib/active_model/errors.rb