Tuesday, September 8, 2009

How to Fix When Rails Validation Doesn't Provide a Helpful Error Message

When you are trying to track down validation issues (like when a <%= error_message_on ... %> is missing), a useful tool is to print out the full_messages to log or in a comment in the page itself. For example in a view you could have:

<!-- errors
Something errors:
<% if @something.errors.full_messages %>
<%= @something.errors.full_messages -%>
<% end %>
-->

Members (attributes) of an ActiveRecord object being validated have their own set of errors. Therefore, when you see a top-level (parent) object's error that says "(Some class) is invalid", you can follow up to find the root cause by printing out the errors of that attribute if it exists.

<!-- errors
Something errors:
<% if @something.errors.full_messages %>
<%= @something.errors.full_messages -%>
<% end %>

SomethingElse errors:
<% if @something.something_else && @something.something_else.errors.full_messages %>
<%= @something.something_else.errors.full_messages -%>
<% end %>
-->

Note: I'm not promoting having errors within comments in your page code. You likely want to avoid that if you can, both because it means more data sent to the user that is not important and because only those looking at page source would see it. This is just something that might be useful during development.

No comments: