Rails validation error not displaying - validates_presence_of, error_message_for

Posted in TDS Developer's Corner by Dawn on the January 7th, 2010

I hit a wall recently as I tried to track down the reason validates_presence_of was not displaying errors. Rails validations normally go off without a hitch, so I was a bit stumped when my attempts to save blank fields were not triggering the appropriate messages. After ensuring my model and view were correct, I fired up the console to make sure my validations were working in the first place. After loading an object and attempting a save, I checked to see if the errors object returned false. Sure enough, all of the validations were enforced.


>> @contact = Contact.find_by_id(9)
=> #
>> @contact.save
=> false
>> @contact.errors.empty?
=> false
>> @contact.errors.count
=> 6
>> @contact.errors.each_full { |msg| puts msg }
   City No blanks
   Zip No blanks
   First name No blanks
   Address No blanks
   Last name No blanks
   State No blanks

After more head banging, I was ready to give up with a simple notification workaround on the update method.


if !@contact.errors.empty?
  flash[:error] = "You are missing required fields."
  redirect_to edit_contact_url(@contact.user)
else
  flash[:notice] = "Successfully saved."
  redirect_to contact_url(@contact.user)
end

That works, but it doesn’t take advantage of the Rails’ error_messages_for helper to display helpful messages and highlight problem fields. Then I realized the initial error. During redirects, the object’s data isn’t passed, so while the validations were enforced (the form data would not save upon submission), no errors were being output to the screen. My new code rendered the page along with the error messages:


if !@contact.errors.empty?
  render :action => 'edit'
else
  flash[:notice] = "Successfully saved."
  redirect_to contact_url(@contact.user)
end

RailsConf Retrospectives, Part 1: Testing

Posted in TDS Developer's Corner by gary on the May 11th, 2009

Show Something Useful

Posted in TDS Developer's Corner by gary on the March 13th, 2009

Catch-all Routes in Rails

Posted in TDS Developer's Corner by Nick on the March 6th, 2009

Use CSS to Mark Fields as Required

Posted in TDS Developer's Corner by Nick on the December 19th, 2008

Testing, shmesting, who needs it?

Posted in TDS Developer's Corner by Paul on the November 24th, 2008

Feeling Lucky

Posted in TDS Developer's Corner by Dawn on the October 27th, 2008

no left turn

Posted in TDS Developer's Corner by PerlPilot on the March 20th, 2007

Web Search API from Y!, Google and MSN

Posted in TDS Developer's Corner by Manasi on the March 21st, 2006