2
votes

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?

2

2 Answers

1
votes

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" } %>
0
votes

Its quite easy.

  1. Install the gem translate_enum

gem install translate_enum

  1. Include TranslateEnum in the model
class Gender < ActiveRecord::Base

include TranslateEnum

enum gender: { male: 0, female: 1}
  1. In the view file:

f.select :gender, options_for_select(Gender.translated_statuses.map {|translation, k, _v| [translation, k] })

  1. Finally in the config/locales/en.yml file:

    activerecord:
     attributes:
       gender:
         gender_list:
           male: "Male"
               female: "Female"
    

Hope this works fine!