Saturday, November 12, 2011

Renaming Attributes the Sneaky Way

The names of your models and their attributes are profoundly important to a Rails application. They become the namesakes to everything else: controllers, views, routes, tests. Users of your application are going to see these names in urls, form fields and validation messages. A few minutes early on can save you hours of find/replace, file renames and broken tests down the road. Sometimes you don't have the luxury of a rename. The shortcut is localization! Let's say your application has a User model with an attribute 'sex'. Those 'Sex can't be blank' validation messages are causing your users existential crises. Let's rename sex to gender. Edit en.yml and add the following:


en:
activerecord:
attributes:
user:
sex: Gender


All your validation and form fields are magically renamed. Voila!

1 comment:

Maedi said...

Very useful, thanks!