Ruby on Rails i18n - Want To Translate Custom Messages in Models
Use a symbol for the message:
validates :email, presence: true, length: { maximum: 60 }, format: { with: valid_email_regex, message: :bad_email }, uniqueness: { case_sensitive: false }
then in the yaml file
[lang]: activerecord: errors: messages: bad_email: "just ain't right"
If there's a translation specific to this model, it will override the general one above:
[lang]: activerecord: errors: models: model_name: # or namespace/model_name attributes: email: bad_email: "model-specific message for invalid email"
If you write custom validations, add_error(:email, :bad_email)
will do the lookup above, but errors[:email] << :bad_email
will not.
I just walked through all this and found the rails guides for custom validators too hard-coded... I'm posting this here even though it's not exactly what you asked, but the Q title fits perfectly (which is why I read this post for my problem).
Custom validation with i18n message:
validate :something_custom?, if: :some_trigger_conditiondef something_custom? if some_error_condition errors.add(:some_field_key, :some_custom_msg) endend# en.ymlactiverecord: errors: models: some_model: some_custom_msg: "This is i18n controlled. yay!"
The solution to this does not need to be custom; The format
validator message already maps to the :invalid
symbol. You need only set the invalid in translation.
en: activerecord: errors: models: some_model: attributes: email: invalid: "FOO"
Reference: http://edgeguides.rubyonrails.org/i18n.html#error-message-interpolation