How to save a model without running callbacks in Rails

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

    To disable en-mass callbacks use...

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

    Then to enable them...

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

    This skips/sets for all instances.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题