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

你。 提交于 2020-01-01 05:12:15

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2493251/how-do-i-override-generic-activerecord-error-messages-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!