Validations and directing errors


#1

I am starting to play with validations as I want to catch errors before
SQL rejects inserts to the table which are ugly when nulls are sent to
‘Not Null’ columns, etc.

If I do something in my model like…

validates_format_of :first_name,
:with => /^\w+$/,
:message => “you moron, enter a name”

I still end up getting the trace window and not the output in the form
itself where I would expect it to display with a first line that reads:

<%= error_messages_for ‘client’ %>

From Agile book and from rails.rubyonrails.com, I can see that I can use
rescue_action_in_public(exception) but that seems to be for trapping
against not found pages.

How do I capture these errors and stay within my form and display my
‘:message’ there?

Craig


#2

Are you redirecting at the end of the action that would have the
validation error? That
tripped me up for a while.

I finally wound up putting the model object in the flash if there were
errors. In my
“add_comment” action, I have:

 if @comment.save
   flash[:notice] = 'Comment added.'
 else
   flash[:comment] = @comment
 end
 redirect_to :action => 'show', :id => @proposal

And then I have to do this in the view:

<% @comment = @flash[:comment]
if(not @comment.nil?)
%>
<%= error_messages_for(:comment)%>
<% end %>

which seems annoying. I want to always redirect so that I never get the
form’s action url
let in the browser address bar.

Now, this may not actually be your problem and there could quite easily
be a cleaner
solution to this. But hopefully I’ll be right about the redirect and
that’ll at least get
you somewhere!

b


#3

I’ve been having exactly the same problem, this works for me.

There must be a cleaner way of doing this, but I’m over my blocker now
so thanks!

Mat.

Ben M. wrote:

Are you redirecting at the end of the action that would have the
validation error? That
tripped me up for a while.

I finally wound up putting the model object in the flash if there were
errors. In my
“add_comment” action, I have:

 if @comment.save
   flash[:notice] = 'Comment added.'
 else
   flash[:comment] = @comment
 end
 redirect_to :action => 'show', :id => @proposal

And then I have to do this in the view:

<% @comment = @flash[:comment]
if(not @comment.nil?)
%>
<%= error_messages_for(:comment)%>
<% end %>

which seems annoying. I want to always redirect so that I never get the
form’s action url
let in the browser address bar.

Now, this may not actually be your problem and there could quite easily
be a cleaner
solution to this. But hopefully I’ll be right about the redirect and
that’ll at least get
you somewhere!

b