Rails模型中around_create回调的目的是什么?

什么时候是around_create回调代码执行,在什么情况下我们应该使用它?

也有这个问题,现在已经找到了答案: around_create允许你在一个方法中基本上同时执行before_createafter_create 。 您必须使用yield来执行之间的保存。

 class MyModel < ActiveRecord::Base around_create :my_callback_method private def my_call_back_method # do some "before_create" stuff here yield # this makes the save happen # do some "after_create" stuff here end end 

刚为我找到一个用例:

想象一下多态观察者的情况,观察者在某些情况下需要在保存之前和之后的其他情况下执行操作。

使用aroundfilter,您可以捕获块中的保存操作并在需要时运行它。

 class SomeClass < ActiveRecord::Base end class SomeClassObserver < ActiveRecord::Observer def around_create(instance, &block) Watcher.perform_action(instance, &block) end end # polymorphic watcher class Watcher def perform_action(some_class, &block) if condition? Watcher::First.perform_action(some_class, &block) else Watcher::Second.perform_action(some_class, &block) end end end class Watcher::First def perform_action(some_class, &block) # update attributes some_class.field = "new value" # save block.call end end class Watcher::Second def perform_action(some_class, &block) # save block.call # Do some stuff with id Mailer.delay.email( some_class.id ) end end 

“around”filter的典型用例是测量性能,或记录或执行其他状态监视或修改。

new?模型调用around_create new? 标志已保存。 它可以用来添加数据来添加/更改模型的值,调用其他方法等等…我不能知道这个回调的具体用例,但它完成了一组“之前,之后,周围”创建操作的回调。 对于查找,更新,保存和删除事件,存在类似的“之前,之后,周围”回调集。

除了Tom Harrison Jr关于记录和监控的答案之外,我发现关键的区别在于控制操作是否完全运行 。 否则,您可以实现自己的before_*after_*回调来执行相同的操作。

around_update为例。 假设您有一个不希望更新运行的情况。 例如,我正在构建一个gem,它将草稿保存在另一个drafts表中,但不保存对“master”表的某些更新。

 around_update :save_update_for_draft private def save_update_for_draft yield if update_base_record? end 

update_base_record?的详细信息update_base_record? 这里引用的方法并不重要。 您可以看到,如果该方法未评估为true ,则更新操作将无法运行。