ruby-on-rails - 从 Rails 模型内部访问翻译文件 (i18n)

标签 ruby-on-rails ruby localization translation rails-i18n

我的模型中有:

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

我希望这些值来自翻译文件“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 方法中设置我的值。

最佳答案

调用:

I18n.t 

而不是简单的 tt 是一个仅在 View 中可用的辅助方法,将整个逻辑委托(delegate)给 I18n 模块。

更新:

如评论中所述, View 助手不仅委托(delegate)给 I18n 模块,它还确保您也可以使用默认范围。

关于ruby-on-rails - 从 Rails 模型内部访问翻译文件 (i18n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21161640/

相关文章:

xcode - 使用 Xcode 10 进行基础国际化

Rails 中的 Mysql 索引行为不当

ruby-on-rails - 重载 ActiveSupport 的默认 to_sentence 行为

ruby-on-rails - 使用 <%= will_paginate %> 更改每页的元素数

javascript - 多语言无法在本地运行,但 codepen 运行良好

c# - 我可以在 ASP.NET 中使用 C# 获取时间参数的本地化缩写吗?

ruby-on-rails - 无法启动 ruby​​ 服务器

ruby-on-rails - Ruby 中的案例陈述

ruby-on-rails - Ruby on rails TypeError(无法将 Hash 转换为整数)

ruby - 如何更改 Jekyll 生成的文件的扩展名?