Is after_validation hook called every time on Active Record?

前端 未结 1 357
小蘑菇
小蘑菇 2021-02-04 06:32

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

相关标签:
1条回答
  • 2021-02-04 07:00

    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.

    0 讨论(0)
提交回复
热议问题