ActiveRecord 回调和验证的顺序是什么? [英] What is the order of ActiveRecord callbacks and validations?
问题描述
我想知道在创建 ActiveRecord 对象时回调和验证的调用顺序是什么.
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 like the following:
validates :reference_code, :if => :reference_code, :on => :create
before_create :assign_reference
哪个会先运行?回调需要先发生,否则验证可能会失败.
which one will run first? The callback needs to happen first or else the validation may fail.
推荐答案
最新版本的 Rails 列表的最新版本可以在 ActiveRecord::Callbacks
文档.Rails 4、3 & 的列表2 个在下面.
The most-up-to-date version of this list for the latest version of Rails can be found in the ActiveRecord::Callbacks
documentation. The lists for Rails 4, 3 & 2 are below.
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 指南.
The most up-to-date version of this list can be found in the 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 指南
The most up-to-date version of this list can be found in the 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
回调或出现在它之后的任何回调中调用我在上面提供的列表.
Since you need to first validate the reference_code
, the assign_reference
method can be called in the after_validation
callback or any callback appearing after it in the list I provided above.
这篇关于ActiveRecord 回调和验证的顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!