Forms and ActiveRecord validation magic

Hi all,

I’ve been digging through the code which scaffold creates (Rails 2).
What I’m am looking for is to determine how does error_messages_for
and form_for determine that ActiveRecord object is completely new and
should be validated before the user has had a chance to input some
data. Basically, the first time the new.html.erb template is run,
error_messages_for does not detect any errors even though the object
is newly created (in the controller’s new method) and does not
validate. But if you then enter data into the input boxes and submit
the form, highlights the validation errors. So the question is how
does it work out when it is being called the first time and should not
validate the inputs?

When I was testing, I put a modelObject.valid? call in the beginning
of the template and that made it highlight errors even before you had
a chance to input any data. So it seems that error_messages_for and
form_for detect this in some way. The question is how? I’ve been
digging through the sources and couldn’t find anything.

Thanks,
gamehack

This is because errors are only created after an explicit call to
#valid?,
#save, or #create.

When you do ARObject.new, nothing has been run and thus nothing has
errored
out.

Also, there’s a new_record? flag set to true.

Next time you do #save or #valid?, yaml out the object, you’ll see an
“errors” attribute filled with the appropriate errors.

Jason

Thank you. I realized that the only difference is that the next time
the method is called, a all to #save would have been made, which would
have triggered the validations which might in turn make
obj.errors.count != 0. So the form functions actually check whether
the number of errors is 0 or not. Thanks for the tip.

g