模型验证中的 Rails 国际化 (I18n):可能与否? [英] Rails Internationalization (I18n) in model validations: Possible or not?
问题描述
我在模型中有以下验证:
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屋!