Another quick Rails lifesaver

October 3rd, 2008

It’s always driven me crazy that the Rails validation macros don’t allow you to override the field name in the error message.

validates_length_of :summary, :maximum => 1500, :too_long => "can not exceed 1,500 characters"

will result in “Summary cannot exceed 1,500 characters”. But the label on the form is Description and the stakeholder wants the message to match the form. Argh.

Well, courtesy of Rails wizard and co-worker Duncan:

# alias attr to the name it has on the form allows us to validate using the form label name and make the message correct
alias_attribute :description, :summary
validates_length_of :description, :maximum => 1500, :too_long => "can not exceed 1,500 characters"

Short, sweet and super-easy. And the Rails docs on validation don’t appear to mention this. I should submit a documentation patch.