Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override generic activerecord error messages in ruby-on-rails?

In my en.yml translation file, I have:

activerecord:
  errors: 
    template: 
       header: 
         one: "1 error prohibited this {{model}} from being saved"
         other: "{{count}} errors prohibited this {{model}} from being saved"  

When an activerecord/validation error occurs during logging into my application, the error message:

"1 error prohibited this user session from being saved"

is displayed (where user_session is the model being used). I'd rather have it say something like

"An error has occured to prevent you from logging into your account".

How do I override the generic error message with my specific one?

like image 658
David Smith Avatar asked Mar 22 '10 15:03

David Smith


1 Answers

I found the routes Rails (2.3.8) follows to translate error messages (with i18n 0.6.0): Also, do not forget to change the full_messages format so that it corresponds with your custom messages.

Here's an example with model "Horse", which validates the attribute "name" (cannot be blank).

In your model(app/models/horse.rb):

validates_presence_of :name

In your translation file (config/locales/en.yml):

en:
  activerecord:
    errors:
      models:
        horse:
          attributes:
            name:
              blank: "Hey, are you the horse with no name?"
      full_messages:
        format: "%{message}"

Below is a link to the RoR-guides page where I found this. There's also a list of which messages are required for every variant of validation.

  • ruby on rails guides example and explanation
  • Table with all validations and corresponding messages

The notation and defaults may change with later versions of Rails and/or i18n.

like image 100
Justus Romijn Avatar answered Nov 16 '22 10:11

Justus Romijn