模型验证中的Rails国际化(I18n):可能吗? [英] Rails Internationalization (I18n) in model validations: Possible or not?

查看:58
本文介绍了模型验证中的Rails国际化(I18n):可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型中具有以下验证:

I have the following validation in a model:

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

翻译似乎无法在生产模式下使用:在所有语言中,总是会翻译英文翻译(可能是因为我在应用中将英语设置为默认语言环境...?).

It seems that the translation does not work in production mode: in all languages it's always the english translation that gets diplayed (probably because I set english as the default locale in my app...?).

所以我假设我们无法转换模型中的验证,因为模型仅加载一次-引导服务器时(然后,将应用默认语言环境).

So I am assuming that we can't translate validations in models, because models get loaded only once - when the server is booted (and then, the default locale would be applied).

我是对的吗?如果是,您将如何解决此问题?

Am I right? If yes, how would you solve this problem?

感谢您的帮助!

推荐答案

解决方案是在模型中不包括任何 custom 消息键,例如...

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')

然后模型将应用默认消息密钥,例如,对于"validates_inclusion_of",将使用:inclusion"

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

...并且在config/locales/en.yml中,您需要具备以下条件:

...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"

作为参考,请查看各自的Rails指南:

for reference, check out the respective Rails guide:

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

这篇关于模型验证中的Rails国际化(I18n):可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆