Rails 4 Active Record Enums are great, but what is the right pattern for translating with i18n?
Try using TranslateEnum gem for these purposes
class Post < ActiveRecord::Base
enum status: { published: 0, archive: 1 }
translate_enum :status
end
Post.translated_status(:published)
Post.translated_statuses
@post = Post.new(status: :published)
@post.translated_status
Try the enum_help gem. From its description:
Help ActiveRecord::Enum feature to work fine with I18n and simple_form.
Heres a t_enum
helper method that I use.
<%= t_enum(@user, :status) %>
enum_helper.rb:
module EnumHelper
def t_enum(inst, enum)
value = inst.send(enum);
t_enum_class(inst.class, enum, value)
end
def t_enum_class(klass, enum, value)
unless value.blank?
I18n.t("activerecord.enums.#{klass.to_s.demodulize.underscore}.#{enum}.#{value}")
end
end
end
user.rb:
class User < ActiveRecord::Base
enum status: [:active, :pending, :archived]
end
en.yml:
en:
activerecord:
enums:
user:
status:
active: "Active"
pending: "Pending..."
archived: "Archived"
Here is a view:
select_tag :gender, options_for_select(Profile.gender_attributes_for_select)
Here is a model (you can move this code into a helper or a decorator actually)
class Profile < ActiveRecord::Base
enum gender: {male: 1, female: 2, trans: 3}
# @return [Array<Array>]
def self.gender_attributes_for_select
genders.map do |gender, _|
[I18n.t("activerecord.attributes.#{model_name.i18n_key}.genders.#{gender}"), gender]
end
end
end
And here is locale file:
en:
activerecord:
attributes:
profile:
genders:
male: Male
female: Female
trans: Trans
Elaborating on user3647358's answer, you can accomplish that very closely to what you're used to when translating attributes names.
Locale file:
en:
activerecord:
attributes:
profile:
genders:
male: Male
female: Female
trans: Trans
Translate by calling I18n#t:
profile = Profile.first
I18n.t(profile.gender, scope: [:activerecord, :attributes, :profile, :genders])
I prefer a simple helper in application_helper
def translate_enum(object, enum_name)
I18n.t("activerecord.attributes.#{object.model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{object.send(enum_name)}")
end
Then in my YML file :
fr:
activerecord:
attributes:
my_model:
my_enum_plural:
pending: "En cours"
accepted: "Accepté"
refused: "Refusé"