Hello in ruby on rails application我为User scaffold构建了一个身份验证系统。
会话控制器
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if !user.nil? && user.authenticate(params[:password])
session[:user_id] == user.id
redirect_to root_url
else
render :new
end
end
def destroy
session[:user_id] == nil
redirect_to login_url
end
end
登录后,我将用户重定向到名为:chat_room
的根页面聊天室控制器
class ChatRoomController < ApplicationController
before_action :authenticate_user
def index
@current_user = User.where(id: params[:user_id]).first
end
end
并在application_controller
中class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def authenticate_user
if session[:user_id] == nil
redirect_to login_path
end
end
end
但是使用此方法,即使凭据正确,该应用也会将我重定向到登录页面。
有人可以帮我吗?
答案 0 :(得分:3)
修正拼写错误:
==
比较
=
作业
def create
user = User.find_by_email(params[:email])
if !user.nil? && user.authenticate(params[:password])
session[:user_id] == user.id
redirect_to root_url
else
render :new
end
end
def destroy
session[:user_id] == nil
redirect_to login_url
end
应该是:
def create
user = User.find_by_email(params[:email])
if !user.nil? && user.authenticate(params[:password])
session[:user_id] **=** user.id
redirect_to root_url
else
render :new
end
end
def destroy
session[:user_id] = nil
redirect_to login_url
end