Solved

Rails: Human Readable Error Messages

Posted on 2008-06-11
1
1,096 Views
Last Modified: 2008-07-17
Is there a way to get Human Readable error messages from the Active Record object?  the default uses the database field name.  Publishing the errors to the web page would be much easier for the user to understand if it said "Last Name can not be blank" rather than "lname can not be blank".  Can this be done without a plugin?

Thanks,
Grant
0
Comment
Question by:renderbox
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 14

Accepted Solution

by:
wesgarrison earned 125 total points
ID: 21766018
You can roll your own messages, but the attribute names are humanized in the standard error messages.  
See code sample (1)
That's why it pays to name your field "last_name" instead of "lname"! You don't really save anything with short field names except a little typing in the migration and it's way paid off in situations like this.

I guess you could do something like code sample (2), if you needed.
(1)
Person.errors.add("first_name", "can't be blank")
Person.errors.full_messages # =>
    ["First name can't be blank"]
 
 
(2)
Person.errors.add("lname", "can't be blank")
err_pretty_names = { "lname" => "Last name", "dob" => "Date of birth", ...}
Person.errors.each do |attr|, |msg| 
  puts "#{err_pretty_names.include?(attr) ? err_pretty_names[attr] :  
    ActiveRecord::Base.human_attribute_name(attr)} - #{msg}"
end

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I recently rediscovered rails when I needed a holiday project and decided to build a management dashboard for the company where I work.  With it being a project done in my free time, I could focus my time on learning the basics rather than trying to…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question