Rails 5:i18n用于命名空间模型的枚举
在命名空间模型中,我对i18n有点困惑。 目前我在模型/app/media/medias.rb中有这样的行:
enum territory: { local: 1, global: 2 }
在模态窗口/views/media/medias/_newmedia.html.erb我有这个:
在/config/locales/models/medias.en.yml我有这个:
en: media: medias: territories: local: Local_EN global: Global_EN
在控制台中我看到查询完成,没有抛出错误,但我的视图没有出现。 当我更改为简单的Media::Medias.territories.keys
我在视图中的下拉列表中显示了键值。 我该如何解决这个问题? 谢谢!
到目前为止,我已经尝试从这个答案中实现代码 。 在视图中它很好地提供了翻译,但是在创建操作时我收到错误,因为它试图保存不是枚举键,而是本地化值。
解决方案
好吧,看来这个答案在我的案例中是解决方案 。 如果有人需要,我的示例应该如何使用命名空间模型:
1)在模型/app/media/medias.rb中
enum territory: { local: 1, global: 2 } def self.territory_attributes_for_select territories.map do |territory, _| [I18n.t("activerecord.attributes.#{model_name.i18n_key}.territories.#{territory}"), territory] end end
2)然后在视图中部分/views/media/medias/_newmedia.html.erb
3)最后在/config/locales/en.yml
en: activerecord: attributes: media/medias: #Important! This is how you define namespaced model! territories: local: "Local EN" global: "Global EN"
我可以确认在视图中显示正确的区域设置,然后在create action中保存值。