2

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!

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.