Search code examples
ruby-on-railsrubyruby-on-rails-3validationskip

How to skip validations when using the `validate` method?


I am using Ruby on Rails 3.2.9. I implemented a custom validator and I would like to skip validations (on creating a new object in a migration file) when using the validate method. In general I can use :without_protection => true as a parameter of the create! method but in my case (see the code below) it seems do not work: validation are not skipped.

class Article < ActiveRecord::Base
  validate do
    # custom validation code
  end
end

How can I skip validations?


Solution

  • You'll have to ensure that all of the other validations are disabled in order for this to be effective. ActiveRecord cannot selectively disable validations, but can omit them entirely.

    For instance:

    class Article < ActiveRecord::Base
      validate :something,
        :if => :validations_are_turned_on?
    
      validate :always
    
    protected
      def validations_are_turned_on?
        !@validations_disabled
      end
    end
    

    Tagging any of the non-essential validations with the appropriate :if condition should work. In this case if @validations_disabled is not set then all validations will run.