Bruno Cabral Bruno Cabral - 10 months ago 51
Ruby Question

Skip Authenticate method in Rails

I have a Sessions controller that requires authentication for creating a session using .authenticate method of has_secure_password defined in the User model, as per below:


class User < ApplicationRecord
before_save { = email.downcase }

# Relationships
has_many :pedidos

# Validations
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :nome, presence: true
validates :empresa, presence: true
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }
validates :cpf, presence: true, length: { minimum: 11, maximum: 14 }
validates :password, presence: true, length: { minimum: 6 }

def admin?


def create
user = User.find_by(email: params[:sessions][:email])
if user && user.authenticate(params[:sessions][:password])
flash[:success] = "Seja bem vindo(a), #{user.nome}!"
session[:user_id] =
redirect_to user
else[:danger] = 'Não foi possível realizar o login, '[:danger] += 'combinação usuário/senha inválido'
render 'new'

Now I created an admin/Users controller that I would like to perform database operations without having to enter password and password_confirmation fields. In the current scenario I'm getting error messages saying "password and password_confirmation can't be blank"

How should I proceed? Thank you.

Answer Source

If presumably your problem is that you'd like to be able to save new Users to your db without needing a password, one way might be to just add a dummy password for admins as explained here

Another might be to skip validations when saving an admin to the db. (I haven't tried this with has_secure_password so I'm not positive that it'd work but worth a shot)