Skyalchemist
Skyalchemist

Reputation: 461

undefined method `user' for nil:NilClass

In my model email token i have

def self.token_valid(token, type)
   return unless token.present?
   token = EmailToken.where("token = ? and verification_type = ? and confirmed = 'false' and created_at <= ?", token, type, EmailToken.expires).includes(:user).first
   user = token.user
 end

And I call this method from my controller

def confirm_password_reset
    @user = EmailToken.token_valid(params[:pass_reset],"password")
    render 'reset_password' if @user
end

The conditions are valid because I've tested it without trying to associate it with the user and it works. What I'm trying to do is to get token_valid method to confirm the token and return both the token and it's associated user. The belongs_to and has_many del have also been defined.
Current error : undefined method user for nil:NilClass
Thanks.

Upvotes: 0

Views: 743

Answers (2)

Tommy Adey
Tommy Adey

Reputation: 816

The best way to go about this is to make your model return token, then in your reset_password view inspect the @user obj

<%= @user.inspect %>

My guess is that it returns and empty array. If you're using sqlite you might want to read this ref doc about boolean data types in sqlite. So you might want to change your confirmed field to 0 for false and 1 for true.

token = EmailToken.where("token = ? and verification_type = ? and confirmed = 0 and created_at <= ?", token, type, EmailToken.expires).includes(:user).first

If not, check spelling mistakes in your tables.

Upvotes: 2

Intrepidd
Intrepidd

Reputation: 20878

This line :

 token = EmailToken.where("token = ? and verification_type = ? and confirmed = 'false' and created_at <= ?", token, type, EmailToken.expires).includes(:user).first

returns nil.

Upvotes: 1

Related Questions