How to save a model without running callbacks in Rails

后端 未结 8 2467
青春惊慌失措
青春惊慌失措 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:51

    If you want to conditionally skip callbacks after checking for each survey you can write your custom method.

    For ex.

    Modified callback

    before_save :calculate_averages, if: Proc.new{ |survey| !survey.skip_callback }
    

    New instance method

    def skip_callback(value = false)
      @skip_callback = @skip_callback ? @skip_callback : value
    end
    

    Script to update surveys

    Survey.all.each do |survey|
      survey.some_average = (survey.some_value + survey.some_other_value) / 2.to_f
      #and some more averages...
      survey.skip_callback(true)
      survey.save!
    end
    

    Its kinda hack but hope will work for you.

提交回复
热议问题