apardes
apardes

Reputation: 4380

Rails skip validation on condition

I'm trying to bypass the password validation for the user model in my application. I have the following based off some similar SO questions:

model.rb

attr_accessor :skip_password_validation
has_secure_password
validates :password, length: { minimum: 6 }, allow_nil: true, unless: :skip_password_validation

controller.rb

@mem.skip_password_validation = true
if @mem.valid?
    #do some stuff
else
    render 'last_template'
end

This consistently renders the last template and returns a password validation error though. Thanks for your help.

Upvotes: 2

Views: 1622

Answers (1)

smathy
smathy

Reputation: 27971

The problem is that as mentioned in the docs has_secure_password adds its own validations:

The following validations are added automatically:

  • Password must be present on creation
  • Password length should be less than or equal to 72 characters
  • Confirmation of password (using a password_confirmation attribute)

Update

Also as mentioned in the docs you can disable the validations by providing the :validations option, setting it to false:

For further customizability, it is possible to supress the default validations by passing validations: false as an argument.

Upvotes: 1

Related Questions