简体   繁体   中英

Ruby on Rails:How to translate options of select tag?

I created a select element in one edit user form with:

t.select :identification_type, User.identification_type_hash

The hash is

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

I need to localize type name. But I didn't find the correct way to add translation into that yml file in locale directory.

I have tryed

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 above works. (while translation of other things still works.) And I failed to find a solution in ROR document.

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

You need to translate the keys yourself, but this is easy. Assume you have the following locale file:

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

Then your select tag can look like the following:

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

Of course this looks quite complicated for the view, so you could move this code to a view helper:

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

So your select tag looks like this:

t.select(:identification_type, user_identification_type_options)

Add the translations in the place where you create identification_type_hash .

You can access the translation function anywhere in Rails via I18n.t() . Documentation .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM