我想知道在创建ActiveRecord对象时调用回调和验证的顺序。
假设我有一些自定义验证&回调如下:
validates :reference_code, :if => :reference_code, :on => :create
before_create :assign_reference
哪一个先运行?回调需要先发生,否则验证可能会失败。
答案 0 :(得分:119)
最新版本的Rails的最新版本列表可以在ActiveRecord::Callbacks
documentation中找到。 Rails列表4,3和& 2是在下面。
此列表的最新版本可在Rails 4 Guides。
中找到before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit/after_rollback
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit/after_rollback
before_destroy
around_destroy
after_destroy
after_commit/after_rollback
此列表的最新版本可在Rails 3 Guides。
中找到before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
before_destroy
around_destroy
after_destroy
此列表的最新版本可在Rails 2.3 Guides
中找到before_validation
before_validation_on_create
after_validation
after_validation_on_create
before_save
before_create
INSERT
操作after_create
after_save
before_validation
before_validation_on_update
after_validation
after_validation_on_update
before_save
before_update
UPDATE
操作after_update
after_save
before_destroy
DELETE
操作 after_destroy
由于您需要先验证reference_code
,因此可以在assign_reference
回调中调用after_validation
方法,或者在我上面提供的列表中显示的任何回调。
答案 1 :(得分:0)
这里是list with all the available Active Record callbacks,按照在相应操作中调用它们的顺序列出:
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit/after_rollback
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit/after_rollback
before_destroy
around_destroy
after_destroy
after_commit/after_rollback
after_save
在创建和更新时都运行,但始终在更具体的回调after_create
和after_update
之后执行,无论宏调用的执行顺序如何。
before_destroy
回调应放置在dependent: :destroy
关联之前(或使用prepend:true选项),以确保它们在记录被dependent: :destroy
删除之前执行。