2

I have the following model:

class User < ActiveRecord::Base
  has_secure_password
  # ...
end

I'm trying to skip validations from has_secure_password helper based on a condition.

So, after searching I found a way in this answer to ALWAYS skip validations, however when I tried to adopt this solution in my case (as I said, I want to skip it based on a condition), as follows:

class User < ActiveRecord::Base
  has_secure_password validations: :super_admin?

  private

  def super_admin?
    p "role #{role.inspect}"
    role == 'super_admin'
  end
end

... it doesn't skip the validation. It doesn't even call the super_admin? method.

Thanks in advance.

1 Answer 1

0

for your case, the one that you need to skip is user.authenticate when you creating session for the user below is sample of creating sesion with logical or if user.super_admin? equal true then it will pass and user can login

class SessionsController < ApplicationController

  def create
    user = User.find_by_username(params[:session][:username])
    if user && (user.super_admin? || user.authenticate(params[:session][:password]))
      login user
      flash[:success] = "Successfully login"
      redirect_to users_path
    else
      flash.now[:error] = 'sorry cannot login'
      render 'new'
    end
  end

end

in user.rb, remove private and check as follow

class User < ActiveRecord::Base

  def super_admin?
    p "role #{role.inspect}"
    role == 'super_admin'
  end
end
Sign up to request clarification or add additional context in comments.

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.