Rails 3 skip validations and callbacks

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

    If the goal is to simply insert or update a record without callbacks or validations, and you would like to do it without resorting to additional gems, adding conditional checks, using RAW SQL, or futzing with your exiting code in any way, it may be possible to use a "shadow object" which points to your existing db table. Like so:

    class ImportedUser < ActiveRecord::Base
      # To import users with no validations or callbacks
      self.table_name = 'users'
    end
    

    This works with every version of Rails, is threadsafe, and completely eliminates all validations and callbacks with no modifications to your existing code. Just remember to use your new class to insert the object, like:

    ImportedUser.new( person_attributes )
    

提交回复
热议问题