Ruby-on-rails 模型验证中的 Rails 国际化 (I18n):可能与否?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4451076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Internationalization (I18n) in model validations: Possible or not?
提问by TomDogg
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?
我对吗?如果是,你将如何解决这个问题?
Thanks for your help!
谢谢你的帮助!
回答by TomDogg
The solution is to NOT include any custommessage 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"
然后模型将应用默认消息键,例如在“validates_inclusion_of”的情况下使用“:inclusion”
...and in config/locales/en.yml you need to have:
...在 config/locales/en.yml 中,您需要:
en:
activerecord:
errors:
models:
my_model:
attributes:
whatever:
inclusion: "Please select whatever." # see default key: "inclusion"
for reference, check out the respective Rails guide:
作为参考,请查看相应的 Rails 指南:
http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
回答by iain
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 guidefor more details.
它将在特定范围内进行翻译。有关更多详细信息,请参阅I18n 指南。
回答by GMsoF
OK, iainanswer works, but I took very long time to figure out where should I put the :select_whatever.
好的,iain答案有效,但我花了很长时间才弄清楚我应该把:select_whatever.
validates_inclusion_of :whatever, :in => [true, false], :message => :select_whatever
validates_inclusion_of :whatever, :in => [true, false], :message => :select_whatever
OK your en.ymlshould look like this:
好的,你en.yml应该是这样的:
en:
errors:
messages:
select_whatever: "error!!"

