从Rails模型内部访问转换文件(i18n) [英] Access translation file (i18n) from inside rails model

查看:73
本文介绍了从Rails模型内部访问转换文件(i18n)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有:

def body_color_enum
  [
    ['Aqua', '#009c9c'],
    ['Grey', '#6d6e71'],
    ['Yellow', '#ffe600'],
    ['White', 'white']
  ]
end

我希望这些值来自翻译文件"en.yml"

I want these values to come from the translation file 'en.yml'

en:
  group:
    hero:
      hex1: '#6d6e71'
      name1: 'Dark grey'
      hex2: '#ccc'
      name2: 'Light grey'
      hex3: '#0099ce'
      name3: 'Blue'
      hex4: '#ffffff'
      name4: 'White'

我已经尝试过了:

def body_color_enum
  [
    [t('group.hero.name1'), '#009c9c'],
    ['Grey', '#6d6e71'],
    ['Yellow', '#ffe600'],
    ['White', 'white']
  ]
end

但是我得到这个错误:

undefined method `t' for #<Group:0x007fabad847ac8>

所以我要问的是如何从模型访问本地文件,以便可以在body_color_enum方法中设置值.

So what I'm asking is how can I access my local file from the model so I can set my values in the body_color_enum method.

推荐答案

致电:

I18n.t 

,而不是简单的t. t是仅在视图中可用的辅助方法,将整个逻辑委托给I18n模块.

instead of simple t. t is a helper method only available in the views, delegating the whole logic to I18n module.

更新:

如评论中所述,视图助手不仅委托给I18n模块,而且还确保您也可以使用默认范围.

As mentioned in the comments, view helper is not only delegating to the I18n module, it makes sure that you can use a default scopes as well.

这篇关于从Rails模型内部访问转换文件(i18n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆