Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

ruby - Access translation file (i18n) from inside rails model

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.

question from:https://stackoverflow.com/questions/21161640/access-translation-file-i18n-from-inside-rails-model

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...