Rails 3 skip validations and callbacks

前端 未结 9 1679
野的像风
野的像风 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:31

    What about adding a method to your model that let's you skip the callbacks?

    class Foo < ActiveRecord::Base
      after_save :do_stuff
    
      def super_secret_create(attrs)
        self.skip_callback(:create)
        self.update_attributes(attrs)
        self.save(:validate => false)
        self.set_callback(:create)
      end
    end
    

    If you end up using something like this, I would recommend using self in the method instead of the model name to avoid connascence of name.

    I also ran across a gist from Sven Fuchs that looks nice, it's here

    0 讨论(0)
  • 2020-12-08 00:32

    This works in Rails 3:

    Model.skip_callback(:create)
    model.save(:validate => false)
    Model.set_callback(:create)
    

    (API docs and related question)

    0 讨论(0)
  • 2020-12-08 00:42

    Use ActiveRecord::Persistence#update_column, like this:

    Model.update_column(field, value)
    
    0 讨论(0)
提交回复
热议问题