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?
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" } %>
Its quite easy.
gem install translate_enum
class Gender < ActiveRecord::Base include TranslateEnum enum gender: { male: 0, female: 1}
f.select :gender, options_for_select(Gender.translated_statuses.map {|translation, k, _v| [translation, k] })
Finally in the config/locales/en.yml
file:
activerecord: attributes: gender: gender_list: male: "Male" female: "Female"
Hope this works fine!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.