Search code examples
ruby-on-railsrubyenumsinternationalizationrails-i18n

Translating Ruby enum symbols with Rails I18n?


Because I'm quite new to Ruby and Rails, I'm not entirely sure about how best to word this question, but here's my situation. I've been tasked with translating a Japanese web app built in Rails to English, and I've mainly been doing that by creating a long list of words/phrases in the config/locales/ja.yml and en.yml files and referencing them in the views by using t('...').

However, I now have a situation where a drop-down selection form is pulling values from a model's enum.

The relevant line in the model:

enum gender: %i(男性 女性)

The relevant line in the view:

<%= f.select :gender, User.genders.keys.to_a, {}, { class: "form-control" } %>

I've been trying various things to little avail, including trying to use solutions involving the enum_help gem.

If possible, I'd like to avoid changing the line in the model, since this is part of a much larger code base that I don't know much about, but if it's necessary, I'll have to. How can I most easily translate the drop-down box to appropriately say "男性" and "女性" for Japanese, but "Male" and "Female" for English?


Solution

  • In config/locales/en for example, you will have:

    views:
      genders:
        male: "Man"
        female: "Lady"
    

    Then in your view:

    <%= f.select :gender, User.genders.keys.collect { |g| [t("views.genders.#{g.downcase}"), g] }, {}, { class: "form-control" } %>