Ruby on Rails: how to translate select tag options?

I created a selection item in one custom edit form with:

t.select :identification_type, User.identification_type_hash

Hash

{ :type_1 => 1, :type_2 => 2, ... }

I need to localize the type name. But I did not find the right way to add the translation to this yml file in the locale directory.

I tried

en_US:
  type_1: Translationg of type 1
  type_2: Translationg of type 1

  active_record:
    attributes:
      identification_type:
        type_1: Translationg of type 1
        type_2: Translationg of type 1

  identification_type:
    type_1: Translationg of type 1
    type_2: Translationg of type 1

No one works above. (while translating other things still works.) And I could not find a solution in the ROR document.

So what is the correct way to localize this hash value?

+4
source share
2 answers

You need to translate the keys yourself, but it's easy. Suppose you have the following locale file:

en_US:
  identification_type:
    type_1: Translationg of type 1
    type_2: Translationg of type 1

Then the tag selectmay look like this:

t.select(:identification_type, 
  User.identification_type_hash.map { |k,v| [t(k, scope: :identification_type), v] })

, , :

module ApplicationHelper
  def user_identification_type_options
    User.identification_type_hash.map do |k,v| 
      [t(k, scope: :identification_type), v]
    end
  end
end

, select :

t.select(:identification_type, user_identification_type_options)
+4

, identification_type_hash.

Rails I18n.t(). .

0

All Articles