Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
Mochimazui Avatar asked Sep 09 '14 19:09

Mochimazui


1 Answers

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)
like image 168
fivedigit Avatar answered Sep 28 '22 14:09

fivedigit