What is purpose of around_create callback in Rails Model?

前端 未结 6 1986
野的像风
野的像风 2021-02-05 15:42

when is around_create callback code executed, in what situations we should use it?

6条回答
  •  感情败类
    2021-02-05 15:47

    Besides Tom Harrison Jr's answer about logging and monitoring, I'm finding that the key differentiator is to gain control over whether or not the operation runs at all. Otherwise, you can implement your own before_* and after_* callbacks to do the same thing.

    Take around_update, for example. Let's say you have a case where you don't want the update to run. For example, I'm building a gem that saves drafts in another drafts table but doesn't save certain updates to the "master" table.

    around_update :save_update_for_draft
    
    private
    
    def save_update_for_draft
      yield if update_base_record?
    end
    

    The details of the update_base_record? method referenced here don't really matter. You can see that the update operation simply won't run if that method doesn't evaluate to true.

提交回复
热议问题