Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate ActiveRecord full error messages?

How can ActiveRecord full error messages be translated? For example, I want to show them in spanish.

I create this file config/locales/es.yml:

es:
  errors:
    attributes:
      email:
        blank: "El email no puede estar en blanco"

But when submitting a form with a presence: true, validation is including the attribute always at the beginning of the message:

Email El email no puede estar en blanco

The first "Email" word is not necessary. How can I get rid of it?

like image 465
David Morales Avatar asked Feb 08 '12 21:02

David Morales


2 Answers

Ok, after much reading and re-reading the official i18n guide, I discovered in the section 5.2.2 this:

ActiveModel::Errors#full_messages prepends the attribute name to the error message using a separator that will be looked up from errors.format (and which defaults to "%{attribute} %{message}").

So, the solution is to configure the format, like this:

es:
  errors:
    format: "%{message}"
    attributes:
      email:
        blank: "El email no puede estar en blanco"
like image 111
David Morales Avatar answered Sep 28 '22 04:09

David Morales


Instead of including the field name in the error message and having to translate each message for each field, you can provide translations for the generic messages and the field names themselves. The generated config/locales/en.yml has a link to more translations: https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale Use the appropriate file(s) downloaded from there and provide translations for field names as demonstrated in the Rails I18n guide: http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

See this answer for an example: https://stackoverflow.com/a/2859275/18038

like image 29
graywh Avatar answered Sep 28 '22 03:09

graywh