Domanda

I am able to create users and sign in, however when I sign out I receive the following (although the session does appear to end):

NoMethodError at /signout

undefined method `update_attribute' for nil:NilClass

This is on the sign_out method in the SessionsHelper, where current_user.update_attribute(...) Does this mean that current_user is nil? What can I do to fix, this. I'm very new to RoR, thanks.

Here's my SessionsHelper

module SessionsHelper

def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.encrypt(remember_token))
    self.current_user = user
end

def signed_in?
    !current_user.nil?
end

def current_user=(user)
    @current_user = user
end

def current_user
    remember_token = User.encrypt(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
end

def sign_out
    current_user.update_attribute(:remember_token, User.encrypt(User.new_remember_token))
    #current_user.update_attribute(:remember_token, User.new_remember_token)
    cookies.delete(:remember_token)
    self.current_user = nil
end

end

Here's my SessionsController class SessionsController < ApplicationController

def new
end

def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
        sign_in user
        redirect_to user
    else
        flash.now[:error] = 'Invalid email/password combination' #not quite right
        render 'new'
    end
end

def destroy
    sign_out
    redirect_to 'signin'
end


end
È stato utile?

Soluzione

it would be nice if you told us what the exact circumstances are that you got this error.

it's quite possible you're going to the sign-out page when you're not actually currently signed-in.

In which case - why don't you add "if signed_in?" to your action eg:

def sign_out
  return unless signed_in? # you are already signed out
  current_user.update_attribute(:remember_token, User.encrypt(User.new_remember_token))
  cookies.delete(:remember_token)
  self.current_user = nil
end

def destroy
  sign_out if signed_in?
  redirect_to 'signin'
end

Alternatively - do you have skip_before_action authenticate_user or similar for sign_out?

Again - to sign out, you have to be signed-in... so you can't skip the authentication action for sign-out.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top