How to save a model without running callbacks in Rails

后端 未结 8 2472
青春惊慌失措
青春惊慌失措 2020-12-29 04:55

I need to calculate values when saving a model in Rails. So I call calculate_averages as a callback for a Survey class:

before_save         


        
8条回答
  •  长情又很酷
    2020-12-29 05:25

    I believe what you are asking for can be achieved with ActiveSupport::Callbacks. Have a look at set_callback and skip_callback.

    In order to "force callbacks to get called even if you made no changes to the record", you need to register the callback to some event e.g. save, validate etc..

    set_callback :save, :before, :my_before_save_callback
    

    To skip the before_save callback, you would do:

    Survey.skip_callback(:save, :before, :calculate_average). 
    

    Please reference the linked ActiveSupport::Callbacks on other supported options such as conditions and blocks to set_callback and skip_callback.

提交回复
热议问题