我通过' railstutorial'来学习。对于第9章,当用户注销浏览器时显示错误undefined method update_attribute for nil:NilClass
(仅当用户未经过身份验证时出现此错误),当用户通过身份验证时,它才能正常运行。
有我的sessions_controller
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
render 'new'
end
end
def destroy
sign_out
redirect_to signin_path
end
end
有我的sessions_helper
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 current_user
remember_token = User.encrypt(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
def signed_in?
!current_user.nil?
end
def sign_out
current_user.update_attribute(:remember_token,
User.encrypt(User.new_remember_token))
cookies.delete(:remember_token)
self.current_user = nil
end
def current_user=(user)
@current_user = user
end
end
抱歉我的英文不好
答案 0 :(得分:1)
当他未登录时,您无法注销用户。
因此,请将destroy
中的SessionsController
操作更改为:
def destroy
sign_out if !signed_in?
redirect_to signin_path
end