What is the order of ActiveRecord callbacks and validations?

前端 未结 2 827
旧巷少年郎
旧巷少年郎 2020-12-04 09:30

I was wondering in what order are callbacks and validations called when an ActiveRecord object is created.

Let’s say I have some custom validations & callbacks l

2条回答
  •  旧巷少年郎
    2020-12-04 09:55

    Rails 5

    Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations:

    1 Creating an Object

    • before_validation
    • after_validation
    • before_save
    • around_save
    • before_create
    • around_create
    • after_create
    • after_save
    • after_commit/after_rollback

    2 Updating an Object

    • before_validation
    • after_validation
    • before_save
    • around_save
    • before_update
    • around_update
    • after_update
    • after_save
    • after_commit/after_rollback

    3 Destroying an Object

    • before_destroy
    • around_destroy
    • after_destroy
    • after_commit/after_rollback

    after_save runs both on create and update, but always after the more specific callbacks after_create and after_update, no matter the order in which the macro calls were executed.

    before_destroy callbacks should be placed before dependent: :destroy associations (or use the prepend: true option), to ensure they execute before the records are deleted by dependent: :destroy.

提交回复
热议问题