Rails Internationalization (I18n) in model validations: Possible or not?

后端 未结 3 1640
南笙
南笙 2020-12-09 07:44

I have the following validation in a model:

validates_inclusion_of :whatever, :in => [true, false], :message => I18n.t(\'please_select_whatever\')
         


        
3条回答
  •  长情又很酷
    2020-12-09 08:28

    The solution is to NOT include any custom message keys in the models, like...

    :message => I18n.t('activerecord.errors.models.my_model.attributes.whatever.please_select_whatever')
    

    The model will then apply the default message keys, for example ":inclusion" in the case of "validates_inclusion_of"

    ...and in config/locales/en.yml you need to have:

    en:
      activerecord:
        errors:
          models:
            my_model:
              attributes:
                whatever:
                  inclusion: "Please select whatever." # see default key: "inclusion"
    

    for reference, check out the respective Rails guide:

    http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

提交回复
热议问题