模型验证中的 Rails 国际化 (I18n):可能吗?
我在模型中进行了以下验证:
validates_inclusion_of :whatever, :in => [true, false], :message => I18n.t('please_select_whatever')
似乎翻译在生产模式下不起作用:在所有语言中,显示的始终是英语翻译(可能是因为我将英语设置为我的应用程序中的默认区域设置...?) 。
因此,我假设我们无法翻译模型中的验证,因为模型仅加载一次 - 当服务器启动时(然后将应用默认区域设置)。
我说得对吗?如果是,你会如何解决这个问题?
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案是不要在模型中包含任何自定义消息键,例如......
然后模型将应用默认消息键,例如在“validates_inclusion_of”的情况下为“:inclusion”
..在 config/locales/en.yml 中,您需要:
作为参考,请查看相应的 Rails 指南:
http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
The solution is to NOT include any custom message keys in the models, like...
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:
for reference, check out the respective Rails guide:
http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
您可以使用符号来指定翻译:
并且它将在特定范围内进行翻译。有关更多详细信息,请参阅I18n 指南。
You can use symbols, to specify translations:
And it will be translated with a particular scope. See the I18n guide for more details.
好的,
iain
答案有效,但我花了很长时间才弄清楚应该将:select_whatever
放在哪里。validates_inclusion_of:无论如何,:in => [true, false], :message => :select_whatever
好的,您的
en.yml
应该如下所示: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: