views:

23

answers:

1

Is after_validation hook called every time, even when the validation is failed? I tried a couple tests and it seems like it!

+3  A: 

You're correct, the validation failure still triggers the after_validation callback. This is the order of callbacks:

  1. before_validation
  2. after_validation
  3. before_save
  4. before_create
  5. after_create
  6. after_save
  7. after_commit

Also, to understand the larger chain of events: the documentation says that a "before" callback that returns false will halt the chain, and halt the action (the save, create, update, etc). An "after" callback that returns false will halt the chain of callbacks, but not the whole action.

"after_validation" is the last thing to run if validations fail, and everything is halted there. If they pass though, everything else is wrapped in a database transaction, and rolled back if something goes wrong. So your "before_create" can create a child object, for instance, and it'll be safely undone if the object creation itself fails.

Jaime Bellmyer
Thank you! Your nailed it. So also, if the after_validation returns false, will it roll back the transaction?
rafamvc
You're welcome! If after_validation returns false, it will halt any further before/after callbacks, but it won't stop the transaction itself. This is probably because "before" callbacks are meant to check for potential problems, "after" callbacks are meant to do whatever side tasks need to be done after a step has been completed successfully. For instance, you might use before_validation to set the default for an attribute, and if that fails you want to stop the whole process. And you might use after_validation to update a "failed_create" counter if there are any errors.
Jaime Bellmyer