Thunder Data Systems

Rails validation error not displaying – validates_presence_of, error_message_for

Rails validation error not displaying – validates_presence_of, error_message_for

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

4 thoughts on “Rails validation error not displaying – validates_presence_of, error_message_for

  1. banderlog

    Great thanks to you man. I thought that my head would explode, but suddenly find this post

Leave a Reply

Your email address will not be published.