當around_create回調代碼執行時,在什麼情況下我們應該使用它?Rails模型中around_create回調的用途是什麼?
13
A
回答
0
around_create
在保存有new?
標誌的模型時被調用。它可以用來添加數據來添加/更改模型的值,調用其他方法等等......我不能回顧這個回調的特定用例,但它完成了一組「前後,後」爲創建操作回叫。對於查找,更新,保存和刪除事件有一個類似的「之前,之後,周圍」回調集。
26
也有這個問題,現在已經找到了答案:around_create
允許你在一個方法中基本上做before_create
和after_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
,則更新操作將無法運行。
相關問題
- 1. 使用事務around_create回調
- 2. drupal form api中「#process」回調的用途是什麼?
- 3. 註冊模型在UVM中的用途是什麼?
- 4. 多態類型的用途是什麼?
- 5. 數組類型的用途是什麼?
- 6. __builtin_offsetof運算符的用途和返回類型是什麼?
- 7. InstanceContext與Duplex服務回調的用途是什麼?
- 8. 爲什麼在Rails模型類中可以調用回調函數?
- 9. 視圖模型定位器的用途是什麼?
- 10. 模型 - 視圖 - 演示者模式中「視圖」的用途是什麼?
- 11. `$ .support.ownLast`的用途是什麼?
- 12. TPopupActionBar的用途是什麼?
- 13. _GLOBAL__I_的用途是什麼?
- 14. $ _POST的用途是什麼?
- 15. 「$ this」的用途是什麼?
- 16. CreateSilverlight.js的用途是什麼?
- 17. vertexAttribPointer的用途是什麼?
- 18. RecognizerIntent.DETAILS_META_DATA的用途是什麼?
- 19. Rake的用途是什麼?
- 20. javax.security.auth.callback。*的用途是什麼?
- 21. config.assets.precompile的用途是什麼?
- 22. is_uploaded_file()的用途是什麼?
- 23. archetypeArtifactId的用途是什麼?
- 24. System.Data.SqlClient.SqlParameter.IsNullable的用途是什麼?
- 25. com.sun.org.apache.xpath.internal.operations.String的用途是什麼?
- 26. FXCollections.unmodifiableObservableList的用途是什麼?
- 27. __init__的用途是什麼?
- 28. __cxa_pure_virtual的用途是什麼?
- 29. cURL的用途是什麼?
- 30. RhoMobile的用途是什麼?