authentication ruby valid_password error

1.3k views Asked by At

I'm new to ROR. I tried for simple login with email and password. I can't authenticate the password. It's repeated question, and my error is not yet cleared with old questions. My code is

 user = User.find_by_email(params[:email])
 user.valid_password?(params[:password])

 if @user = User.find_by_email(params[:user][:email]).valid_password?(params[:user][:password])
    #render :json=> user.as_json(:status=>'success', :Message=>'Sucessfully Registered', :username=>user.username ), :status=>201
    render :json=> {userDetails: [{:status=>'Success',:Message=>'Successfully Signed in', :username=>@user.name, :useremail=>@user.email, :usermobile=>@user.mobile_no }]}, :status=>200
 else
   render :json=> {:status=>'Failure',:message=>'Invalid Credentials'}, :status=>422
   :message=>'Sucessfully Singed in', :auth_token=>user.authentication_token, :email=>user.email), :status=>201
  end

I'm facing the below error

undefined method `valid_password?' for nil:NilClass

could anyone tell me what i'm doing incorrectly?

3

There are 3 answers

1
Max Williams On BEST ANSWER

change the if line to

if (@user = User.find_by_email(params[:user][:email])) && @user.valid_password?(params[:user][:password])
1
teoreda On
user = User.find_by_email(params[:email])

User.find_by_email(params[:email]) returns nil (can't find), thus user is nil, and Rails is telling you that the nil class doesn't have a valid_password? method.

EDIT

You are calling a method User.find_by_email(params[:email]) that has nil as result. So in simple words you didn't find records.

EDIT v2

You could check the content of user for debugging purpose by using a code like:

if !user.nil?
  puts "#{user}"
else 
  puts "user is nil!"
end
0
Pardeep Saini On

Just check user . I think your query with User.find_by_email(params[:emil]) return a nil .thats why you getting the undefined method `valid_password?' for nil:NilClass .