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

心不动则不痛 提交于 2019-11-28 08:01:30
TomDogg

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

You can use symbols, to specify translations:

validates_inclusion_of :whatever, :in => [true, false], :message => :select_whatever

And it will be translated with a particular scope. See the I18n guide for more details.

OK, iain answer works, but I took very long time to figure out where should I put the :select_whatever.

validates_inclusion_of :whatever, :in => [true, false], :message => :select_whatever

OK your en.yml should look like this:

en:
  errors:
    messages:
      select_whatever: "error!!"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!