max
max

Reputation: 167

How to skip all validations in Rails?

I have a regular Rails model with many validations. The model has a skip_validations column. When an object has skip_validations: true, I want to be able to update the object without running any validations.

Is there any way to do this without adding an unless option to every validation? -- (for example unless: Proc.new { |obj| obj.skip_validations == true })

Thank you!

Upvotes: 2

Views: 1394

Answers (3)

max
max

Reputation: 167

Another possible answer (not recommended) is to overwrite the valid? method inside the model.

def valid?(*args)
  if self.skip_validations
    return true
  end
  super(args)
end

Upvotes: 1

Prabakaran
Prabakaran

Reputation: 353

Instead of having a field deliberately to skip validations, you can pass validate: false to the save method.

Please take a look at this

P.S: Better to stay away from reinventing the wheel.

Upvotes: 3

Anuj
Anuj

Reputation: 1940

You can group all the conditional validations together, as documented here https://edgeguides.rubyonrails.org/active_record_validations.html#grouping-conditional-validations

class User < ApplicationRecord
  with_options unless: Proc.new { |obj| obj.skip_validations == true } do |obj|
    obj.validates :password, length: { minimum: 10 }
    ...
  end
end

Upvotes: 1

Related Questions