Overwrite rails error message format only for custom error messages

Viewed 242

Is there a way to overwrite the message format only for custom error messages?

I know that it is possible to overwrite rails error message formats at the attribute and model level by using

en:   
  errors:
    format: '%{message}'

or

en:
  activemodel:
    errors:
      models:
        person:
          format: '%{message}'

or

en:
  activemodel:
    errors:
      models:
        person:
          attributes:
            name:
              format: '%{message}'

source (https://github.com/rails/rails/pull/32956).

The issue with this approach, no matter which level the format is overwritten at, this always overwrites the format for all default rails error messages. If I have a model Person with an attribute name and I add a en.yml config like

en:
  activemodel:
    errors:
      models:
        person:
          attributes:
            name:
              older_than_eighteen: "You must be older than eighteen"
              format: '%{message}'

this now leads to all error message for the name attribute of person being interpolated without the attribute name. If I got some validate :name, presence: true the error message for a blank name becomes can't be blank instead of Name can't be blank. I know that I could add another error message to the en.yml file above like blank: "Name can't be blank" but I would like to avoid that and instead only change the format for my custom error message.

Is there a way to achieve this?

1 Answers

add into your config/application.rb

config.active_model.i18n_customize_full_message = true

According to the RoR official docs:

Controls whether the Error#full_message format can be overridden in an i18n locale file. Defaults to false. When set to true, full_message will look for a format at the attribute and model level of the locale files. The default format is "%{attribute} %{message}", where attribute is the name of the attribute, and message is the validation-specific message. The following example overrides the format for all Person attributes, as well as the format for a specific Person attribute (age).

Related