按照Railstutorial.org的指示,我正在从头开始构建身份验证功能(与使用gem相对)。我正在尝试使用户注销。根据9.1.3节,这应该很简单。但是我缺少一些东西。我已经重读了这本书几次,以尝试发现我的错误,并且当然在这里尝试了有关stackoverflow的建议。
以下是我尝试过的一些建议
添加csrf-meta标签
ActionController::InvalidAuthenticityToken in SessionsController#destroy
将'session.delete(:user_id)'替换为'reset_session'
NoMethodError in SessionsController#destroy
我已经将我的代码与另一个“学生” github文件进行了比较
https://github.com/becky000/sample_app/tree/master/app
除了我使用的ruby和rails版本之外,没有发现主要区别。红宝石'2.5.3'和'rails','〜> 5.2.3'。
尝试注销时,我得到
ActionController :: InvalidAuthenticityToken在SessionsController#destroy中
参数:
{“ _ method” =>“删除”}
我认为这意味着我的destroy方法有问题。但是,据我所知,我已经遵循了有关T的说明。
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
@user = User.find_by(email: params[:session][:email].downcase)
if @user && @user.authenticate(params[:session][:password])
log_in @user
params[:session][:remember_me] == '1' ? remember(@user) :
forget(@user)
redirect_back_or @user
else
# Create an error message.
flash.now[:danger] = 'not relevant'
render 'new'
end
end
def destroy
log_out if logged_in?
redirect_to root_url
end
end
app/helpers/sessions_helper.rb
module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
def current_user?(user)
user == current_user
end
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
def logged_in?
!current_user.nil?
end
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
end
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
@user = User.find_by(email: params[:session][:email].downcase)
if @user && @user.authenticate(params[:session][:password])
# Log the user in and redirect to the user's show page
log_in user
remember user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out if logged_in?
redirect_to root_url
end
end