Custom error messages in validations - Rails3 - Part#1 The Quick Answer

The default error messages when scaffolding a model always put the name of the attribute as first word in the error sentence.

What if, instead of getting the default validation error messages, we wanted something like "Sorry, Name can't be blank!"? In the model, if you just set the :message option like:

1
validates_presence_of :name, :message => "Sorry, Name can't be blank"

...you are gonna get something like "NameSorry, Name can't be blank"

While researching, I found many ways to accomplish this, but first I am gonna show the way I think is the best (in case you are looking for some quick answer), and later I'm gonna explain the other ways and why I think this is the best, and hopefully you'r gonna understand how this works (it's not that hard.)

How to get customized error messages in rails 3 validations?

The quick answer:

keep this in your model:

1
validates_presence_of :name, :message => "Sorry, Name can't be blank"

and in the view, instead of leaving

1
2
3
<% @instance.errors.full_messages.each do |msg| %><br />
    <li><%= msg %></li><br />
<% end %><br />

...as it would be when we use the scaffold generator, replace by:

1
2
3
 <% @instance.errors.each do |attr, msg| %><br />
   <li><%= msg %></li><br />
 <% end %><br />

And you will get just the message you especified in the model, without the attribute name!

Maybe, that was enough for you to figure it all out, if it wasn't, in next post I'll show how it woks in details, in case you are wondering. Here it is.