Tom*_*ogg 38 validation model ruby-on-rails internationalization production-environment
我在模型中进行了以下验证:
validates_inclusion_of :whatever, :in => [true, false], :message => I18n.t('please_select_whatever')
Run Code Online (Sandbox Code Playgroud)
似乎翻译在生产模式下不起作用:在所有语言中,它始终是英语翻译(可能因为我将英语设置为我的应用程序中的默认语言环境......?).
所以我假设我们不能在模型中转换验证,因为模型只加载一次 - 当服务器被引导时(然后,将应用默认的语言环境).
我对吗?如果是的话,你会如何解决这个问题?
谢谢你的帮助!
Tom*_*ogg 49
解决方案是不在模型中包含任何自定义消息密钥,例如......
:message => I18n.t('activerecord.errors.models.my_model.attributes.whatever.please_select_whatever')
Run Code Online (Sandbox Code Playgroud)
然后,模型将应用默认消息密钥,例如"validates_inclusion_of"中的":inclusion"
...在config/locales/en.yml中你需要:
en:
activerecord:
errors:
models:
my_model:
attributes:
whatever:
inclusion: "Please select whatever." # see default key: "inclusion"
Run Code Online (Sandbox Code Playgroud)
供参考,请查看相应的Rails指南:
http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
iai*_*ain 17
您可以使用符号来指定翻译:
validates_inclusion_of :whatever, :in => [true, false], :message => :select_whatever
Run Code Online (Sandbox Code Playgroud)
它将在特定范围内进行翻译.有关详细信息,请参阅I18n指南.
好的,iain答案有效,但我花了很长时间才弄清楚我应该把:select_whatever.
validates_inclusion_of :whatever, :in => [true, false], :message => :select_whatever
好的,你en.yml应该是这样的:
en:
errors:
messages:
select_whatever: "error!!"
Run Code Online (Sandbox Code Playgroud)