Home > Software design >  How can internationalized(translated) array's value of rails model?
How can internationalized(translated) array's value of rails model?

Time:10-12

This section is present in model, we use this for form submission.

GENDER_TYPES = %w[Male Female Other]

CodePudding user response:

I'm not sure if this works for you but what I do in this case is using a (Rails enum). In your model:

class MyModel < ApplicationRecord
  enum gender: [:male, :female, :other]
end

My ApplicationRecord class:

   class ApplicationRecord < ActiveRecord::Base
     self.abstract_class = true

     def self.enum_t(enum_name, enum_value)
       I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{enum_value}")
     end
   end

In my en.yml:

  en:
    activerecord:
      attributes:
        my_model:
          genders:
            male: Male
            female: Female
            other: Other

In my view to create a select:

f.select :gender, MyModel.genders.keys.collect { |gender| [MyModel.enum_t(:gender, gender), gender] }

Or show action:

= MyModel.enum_t(:gender, my_model.gender)
  • Related