When using the create and update methods, is there anyway of confirming that the create/update method was unsuccessful- e.g. if it failed validation? The API documentation and playing around in the console suggest that it fails silently.
With a create, I could always check if the object's id has been set - but what would one do on an update?
With a create, I could always check if the object's id has been set -
but what would one do on an update?
They return true/false. the ! variants raise an exception instead. You can always call the valid? method to see if an object's validations pass.
Fred
<snip>
Hi Fred
Thanks for that - wasn't aware there is a create! and update!. Just a note - according to the api docs:
create(attributes = nil)
Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.
But I will just catch the exception from create! and update!.
So , would it be recommended to use this method (checking @alert.errors)
versus catching an exception from the save! or create! or update! ?
we mostly use the "if @alert.save then" version
Freds way with the exceptions is good too of course
just a matter of taste (or maybe Fred can enlighten us, if it has
additional advantages). i just like to handle errors where they happen
to be and with the rescue handling for exceptions you end up with a bit
more code, i think
i mentioned the errors object mainly because it's another alternative
and useful for other purposes (show errors to the user, logger.info
errors for debugging)
if @alert.errors.size > 0 ...
the error object is handy anyway, since it will contain all those errors from your validations
<snip>
One more question - is there anyway that the method could have completed and produced errors? Or is errors.size > 1 a guarantee that the operation failed?