Custom field names in Rails error messages

Posted by Madhan ayyasamy on Mad Han RoR Tips See other posts from Mad Han RoR Tips or by Madhan ayyasamy
Published on 2010-07-06T04:57:00.000-07:00 Indexed on 2010/12/06 16:59 UTC
Read the original article Hit count: 306

Filed under:
The defaults in Rails with ActiveRecord is beautiful when you are just getting started and are created everything for the first time. But once you get into it and your database schema becomes a little more solidified, the things that would have been easy to do by relying on the conventions of Rails require a little bit more work.

In my case, I had a form where there was a database column named “num_guests”, representing the number of guests. When the field fails to pass validation, the error messages is something like

Num guests is not a number

Not quite the text that we want. It would be better if it said

Number of guests is not a number

After doing a little bit of digging, I found the human_attribute_name method. You can override this method in your model class to provide alternative names for fields. To change our error message, I did the following
class Reservation < ActiveRecord::Base
...
validates_presence_of :num_guests
...
HUMAN_ATTRIBUTES = {
:num_guests => "Number of guests"
}

def self.human_attribute_name(attr)
HUMAN_ATTRIBUTES[attr.to_sym] || super
end
end
Since Rails 2.2, this method is used to support internationalization (i18n). Looking at it, it reminds me of Java’s Resource Bundles and Spring MVC’s error messages. Messages are defined based off a key and there’s a chain of look ups that get applied to resolve an error’s message.

Although, I don’t see myself doing any i18n work in the near-term, it is cool that we have that option now in Rails.

© Mad Han RoR Tips or respective owner

Related posts about Ruby On Rails