How to translate active record model validations

前端 未结 3 1866
[愿得一人]
[愿得一人] 2021-02-01 03:05

When I submit a form with an error in it, it returns an error message. How can I translate these error messages with i18n? I already have translation for all the other texts in

相关标签:
3条回答
  • 2021-02-01 03:31

    The rails I18n guide covers this pretty well.

    You can put the following in config/locales/nl.yml to translate the attributes:

    nl:
      activerecord:
        models:
          user: "User"
        attributes:
          email: "Email"
    

    For the error messages, ActiveRecord will look them up in the following namespaces:

    activerecord.errors.models.[model_name].attributes.[attribute_name]
    activerecord.errors.models.[model_name]
    activerecord.errors.messages
    errors.attributes.[attribute_name]
    errors.messages
    

    model, attribute and value are interpolated and available in your translations, for example:

    nl:
      errors:
        messages:
          blank: "Please fill the %{model}'s %{attribute}"
    
    0 讨论(0)
  • 2021-02-01 03:37

    Just use the Dutch translations file that you can find here. It contains translations for most (if not all) ActiveRecord validation messages.

    Copy the file to config/locales/ in your project.

    Alternate method

    If you want to benefit from updated translations, add the following to your Gemfile instead of copying the translation files by hand:

    gem 'rails-i18n'
    
    0 讨论(0)
  • 2021-02-01 03:40

    The translation for the title would be:

    nl:
      activerecord:
        errors:
          template:
            header:
              one:   "1 error prohibited this %{model} from being saved"
              other: "%{count} errors prohibited this %{model} from being saved"
            body:    "There were problems with the following fields:"
    

    For translating the error messages, Rails will use the following order of translations:

    activerecord.errors.models.user.attributes.name.blank
    activerecord.errors.models.user.blank
    activerecord.errors.messages.blank
    errors.attributes.name.blank
    errors.messages.blank
    

    So you could add:

    nl:
      activerecord:
        errors:
          models:
            user:
              attributes:
                email:
                  blank: "foo blank in nl bar baz"
    

    It's documented in the Rails Internationalization (I18n) API Guide, which might give you some more insight.

    0 讨论(0)
提交回复
热议问题