Solved

Rails: Human Readable Error Messages

Posted on 2008-06-11
1
1,032 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
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Article by: narshlob
If you've ever programmed in Ruby and have come across either a proc or a lambda, you might have been wondering what the difference is between the two and when you would use one over the other. This article will try to explain the difference between…
In Ruby, Call or invoke a API DLL library is easily via Win32API class, win32-api gem or other gems. For general DLL API call, there are quite a few references, some good tips list below: http://www.rubytips.org/2008/05/13/accessing-windows-api-fro…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

757 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now