Rails: How to use i18n with Rails 4 enums

后端 未结 16 2248
天涯浪人
天涯浪人 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: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}")
    

提交回复
热议问题