Ruby on Rails: how to set up a validation error message?

I have the following code:

validates :name, :presence => true 

An error message was received: "The name cannot be empty" Instead of using the name of the actual attribute (in this case "name"), I want to display the message as "Registration name cannot be empty." How to overwrite the default message for validation? I tried to add: a message but this did not work ...

Thanks!

+6
source share
3 answers

In the en.yml file, define user keys as:

 activerecord: attributes: model_name: attribute_name1: key1 attribute_name2: key2 ...... 

This key will be used automatically when errors occur.

Link: http://edgeguides.rubyonrails.org/i18n.html#translations-for-active-record-models (5.1 Translations for active recording models)

+13
source

This will do the trick:

 validates :name, presence: { message: "Registration name can't be blank" } 

or the syntax version of the old hash version:

 validates :name, :presence => { :message => "Registration name can't be blank" } 
+7
source

It's a bit late (after about 35 days) to answer this. So, sorry for that. But I just wanted to share the fact that I used the gem more than a few months ago for custom error messages.

This plugin allows you to omit the attribute name for specific messages. All you have to do is start a message with the symbol "^".

I just checked it https://github.com/nwise/custom_error_message & amp; It has not been updated since March. So I probably used it at the right time.

ps: Your answer for defining user keys in a yml file is more appropriate.

+6
source

Source: https://habr.com/ru/post/898730/


All Articles