2011-03-28 58 views

回答

0

around_create在保存有new?標誌的模型時被調用。它可以用來添加數據來添加/更改模型的值,調用其他方法等等......我不能回顧這個回調的特定用例,但它完成了一組「前後,後」爲創建操作回叫。對於查找,更新,保存和刪除事件有一個類似的「之前,之後,周圍」回調集。

26

也有這個問題,現在已經找到了答案: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 
1

「around」過濾器的一個經典用例是測量性能,或記錄或執行其他狀態監視或修改。

3

剛剛發現我一個用例:

試想在某些情況下多態守望者的情況和觀察者之前需要執行操作保存和之後其他案件。

使用around filter可以捕獲塊中的保存操作並在需要時運行它。

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 
0

除了Tom Harrison Jr's answer有關記錄和監視,我發現的主要區別是在操作是否根本運行增益控制。否則,你可以實現你自己的before_*after_*回調做同樣的事情。例如,可以使用around_update。假設你有一個你不希望更新運行的情況。例如,我正在構建一個將另一個drafts表中的草稿進行保存的gem,但不會將某些更新保存到「主」表中。

around_update :save_update_for_draft 

private 

def save_update_for_draft 
    yield if update_base_record? 
end 

此處引用的update_base_record?方法的詳細信息並不重要。您可以看到,如果該方法未計算爲true,則更新操作將無法運行。