How do I override generic activerecord error messa

2020-06-16 08:56发布

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?

2条回答
做个烂人
2楼-- · 2020-06-16 09:19

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.

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

查看更多
▲ chillily
3楼-- · 2020-06-16 09:26

You need to make your own FormBuilder and change it's translation key.

查看更多
登录 后发表回答