Rails: How to use i18n with Rails 4 enums

后端 未结 16 2120
天涯浪人
天涯浪人 2020-11-28 04:10

Rails 4 Active Record Enums are great, but what is the right pattern for translating with i18n?

相关标签:
16条回答
  • 2020-11-28 04:49

    Model:

    enum stage: { starting: 1, course: 2, ending: 3 }
    
    def self.i18n_stages(hash = {})
      stages.keys.each { |key| hash[I18n.t("checkpoint_stages.#{key}")] = key }
      hash
    end
    

    Locale:

    checkpoint_stages:
        starting: Saída
        course: Percurso
        ending: Chegada
    

    And on the view (.slim):

    = f.input_field :stage, collection: Checkpoint.i18n_stages, as: :radio_buttons
    
    0 讨论(0)
  • 2020-11-28 04:50
    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      def self.enum(definitions)
        defind_i18n_text(definitions) if definitions.delete(:_human)
        super(definitions)
      end
    
      def self.defind_i18n_text(definitions)
        scope = i18n_scope
        definitions.each do |name, values|
          next if name.to_s.start_with?('_')
          define_singleton_method("human_#{name.to_s.tableize}") do
            p values
            values.map { |key, _value| [key, I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{key}")] }.to_h
          end
    
          define_method("human_#{name}") do
            I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{send(name)}")
          end
        end
      end
    end
    
    
    en:
      activerecord:
        enums:
          mymodel:
            my_somethings:
               my_enum_value: "My enum Value!"
    
    enum status: [:unread, :down], _human: true
    
    0 讨论(0)
  • 2020-11-28 04:52

    I didn't find any specific pattern either, so I simply added:

    en:
      user_status:
        active:   Active
        pending:  Pending...
        archived: Archived
    

    to an arbitrary .yml file. Then in my views:

    I18n.t :"user_status.#{user.status}"
    
    0 讨论(0)
  • 2020-11-28 04:55

    To keep the internationalization similar as any other attribute I followed the nested attribute way as you can see here.

    If you have a class User:

    class User < ActiveRecord::Base
      enum role: [ :teacher, :coordinator ]
    end
    

    And a yml like this:

    pt-BR:
      activerecord:
        attributes:
          user/role: # You need to nest the values under model_name/attribute_name
            coordinator: Coordenador
            teacher: Professor
    

    You can use:

    User.human_attribute_name("role.#{@user.role}")
    
    0 讨论(0)
提交回复
热议问题