The Pug Automatic

Full error messages without prepended attribute name

Written December 19, 2007. Tagged Ruby, Ruby on Rails.

In your Rails validations, you can add errors to base or to a specific attribute. When you add errors to an attribute, the full error messages (used e.g. by error_messages_for) are prepended by the (humanized) attribute name.

Sometimes this isn't what I want. Here's a quick hack to not prepend the attribute name if the error message starts with an upper case character.

Just stick this in lib/less_full_error_messages.rb, and require that file from environment.rb:

class ActiveRecord::Errors
def full_messages
full_messages = []

@errors.each_key do |attr|
@errors[attr].each do |msg|
next if msg.nil?

if attr == "base" || msg =~ /^[[:upper:]]/
full_messages << msg
else
full_messages << @base.class.human_attribute_name(attr) + " " + msg
end
end
end
full_messages
end
end

Now,

errors.add('name', "is just silly") if name.just_silly?
errors.add('born_at', "You're too young") if age < AGE_LIMIT

will result in the full error messages

Name is just silly
You're too young