Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is after_validation hook called every time on Active Record?

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

like image 754
rafamvc Avatar asked Oct 27 '10 00:10

rafamvc


1 Answers

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.

like image 69
Jaime Bellmyer Avatar answered Oct 13 '22 00:10

Jaime Bellmyer