Tuesday, February 10, 2015

Labeling Rails Enums

Rails 4.1 introduced ActiveRecord Enums, a handy little feature that lets you store an integer in a database column, but use symbols or strings in your code.  Until today, I've been presenting these in select boxes with code like this:

This generates a perfectly acceptable select box if you don't need internationalization and the enum names you've picked are good enough to present to the user.  If thats not the case, or you to change the presentation without changing the code, a new helper method leveraging Ruby's internationalization (i18n) features can be a good approach.

Keep reading for how I changed the presentation of enumerations in a drop down without changing my models or renaming the enumeration names.


Here is how we can provide alternate labels for some of our drop down values.

First, create a new helper that will pass each enumeration name through i18n to perform a label conversation

Second, change your form to call the helper

Third, provide the translations.

Before translation:













After translation:


A few notes:
  • If the translation is missing, the code's default is to fall back to the titleized text.  If you want to omit options where the translation is missing,  You can modify the methods to call enum_to_translated_option with a default of blank and the blank options will be removed from the select.
  • enum_to_translated_option is useful in a show template.  
  • It may be useful to sort the options after translation.  That is an easy addition to the helper.

Is this useful for you?  Is there a better way?  Let me know!

No comments:

Post a Comment