Localized ActiveRecord::Enum Display Names

In a previous post, we added an ActiveRecord::Enum attribute to a Rails model. Pretty straightforward. One issue I noticed was the use of humanize or titleize to get a display name for views and selects.

In simple examples, this is fine, but in the real world you will likely need an alternate display name either for different languages or just different wording. A status of error456, for example, makes sense in the code but the user would probably prefer to see Cannot save record.

Localization files to the rescue. A quick how-to using the Projects example.

(1) Add the following two methods. In the example, they’re part of the Project model but in the real world you probably want them in a presenter or decorator or even a helper.

(2) In a new or existing file in config/locales, add the following section:

(3) In your views, you would then just call < %= @project.display_status %>. This will display either the string found in the locale file or the status titleized by default.

If the status is selected from a drop down, for example, in a form_for block you would use
< %= f.select :status, options_for_select(Project.status_names_for_select, selected: @project.status), {} , class: "form-control" %>