3

In Rails 3, the validators is changed: now is possible to specify all the validators for a specific field in once:

so instead to write

Rails 2.x.x style
validates_size_of :username, :within => 5..15, :message=> "username size must be between 5 and 15"

now I can write

Rails 3 style

 validates :username,  :length => { :minimum => 5, :maximum => 40 }

But if I add :messge=> "bla bla bla" in this last example (Rails 3 style) an error occur, so the question is: How to edit personal error message to the model in order to show them in the view ?

Thank you

1 Answer 1

1

When you use the shorthand validates :model method you can only add specific messages within the context of a specific validator. Example:

validates :username, :length => { :minimum => 5, :maximum => 40, :message => 'should be between 5 and 40 characters' }

Note that the message is in the hash for the :length key. Otherwise Rails doesn't know which validator the message should be applied to.

Sign up to request clarification or add additional context in comments.

3 Comments

And what about the syntax errors.add ? How can I add a specific error from the model ? is it an equivalent tecnique with the one you cited ?
Can you give me a simple example to use errors.add instead that :message in your code ? Thank you very much
If you want to add a custom error message, you can still use :message but call a method to generate the error message instead of having a literal string. Otherwise you can code a totally custom set of validation logic including custom logic to generate your error message. This blog post has examples. thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.