41

What I have in my model is:

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

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'

I have tried this:

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

But i get this error:

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

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.

Jake McAllister
  • 1,037
  • 3
  • 12
  • 29

2 Answers2

107

Call:

I18n.t 

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

UPDATE:

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.

BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • 10
    To explain why: this happens because `t` is a view helper. View helpers are not available in models (among other places), so the full call to `I18n.t` is needed. – joanwolk Nov 06 '14 at 09:37
  • 1
    Lovely stuff. I needed this to access i18n within a "cell" - worked like a charm. – Mikey Hogarth Mar 10 '15 at 16:22
  • 2
    it's worth mentioning, that `I18n.t` is not the same as calling `translate` in view https://github.com/rails/rails/blob/v5.1.1/actionview/lib/action_view/helpers/translation_helper.rb#L18 – Artur INTECH Jun 20 '17 at 17:40
  • Any way to make I18n helper available in model, so we can just call `t()` instead of `I18n.t`? Many valid use cases for calling translations from within the model, including customizing error messages on validations, etc. .. – Aaron Wallentine Aug 28 '22 at 04:19
2
# constants
def self.option_enum
    [ 
      [ I18n.t('enum.amount'), 'A' ], 
      [ I18n.t('enum.percentage'), 'P' ] 
    ]
end
G. I. Joe
  • 1,585
  • 17
  • 21
  • This simply won't work with languages like German where every noun start with a capital letter. Capitalization is a matter of the language itself and should not be "fixed" inside the code – BroiSatse Jul 13 '17 at 18:11