Rails 3 skip validations and callbacks

前端 未结 9 1677
野的像风
野的像风 2020-12-07 23:58

I have a particularly complex model with validations and callbacks defined. The business needs now calls for a particular scenario where adding a new record requires skippin

9条回答
  •  太阳男子
    2020-12-08 00:26

    My take was like this (note: this disables callbacks on create, for update, delete and others you need to add them to array).

        begin
          [:create, :save].each{|a| self.class.skip_callback(a) } # We disable callbacks on save and create
    
          # create new record here without callbacks, tou can also disable validations with 
          # .save(:validate => false)
        ensure
          [:create, :save].each{|a| self.class.set_callback(a) }  # and we ensure that callbacks are restored
        end
    

提交回复
热议问题