Skip to content

Instantly share code, notes, and snippets.

@abevoelker
Last active July 11, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abevoelker/fed59c2ec908de15acd27965e4725762 to your computer and use it in GitHub Desktop.
Save abevoelker/fed59c2ec908de15acd27965e4725762 to your computer and use it in GitHub Desktop.
# app/helpers/application_helper.rb
module ApplicationHelper
def human_enum_name(model, attr)
I18n.t("activerecord.attributes.#{model.model_name.i18n_key}.#{attr.to_s}.#{model.send(attr)}")
end
end
# human_enum_name(@user, :status)
@jdsampayo
Copy link

jdsampayo commented Jul 11, 2021

Very helpful, I just suggest to add something to the #{attr.to_s} key in your helper, like #{attr.to_s}_types otherwise you can't use the human attribute method as it will have the hash instead a string and will mark an error, example:

# in your view, now you can use it hover the column
<%=Pet.human_attribute_name(:gender)%> # => Género

# and hover the values
<%=human_enum_name(pet, :gender)%> # => Macho
# in your locales use '_types' to avoid override the column
es:
  activerecord:
    models:
      attributes:
       pet:
         gender: Género
         gender_types:
           unknown: Desconocido
           female: Hembra
           male: Macho

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment