我的rails身份验证存在问题。我没有使用Devise。无论出于何种原因,当我登录到应用程序时,一切都很好但是当我在创建新帐户时尝试重定向时,current_user是nil?有什么建议吗?
用户模型
class UsersController < ApplicationController
before_action :set_user, only: [:show]
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "Welcome to the site"
redirect_to current_user
else
flash[:notice] = "There was a problem creating your account. Please try again."
render new
end
end
def new
@user = User.new
end
def show
@locations = current_user.locations
@appointments = current_user.appointments
end
def index
end
private
def set_user
@user = User.find_by_email(params[:id])
end
def user_params
params.require(:user).permit(:name, :email, :service, :provider, :password, :password_confirmation)
end
end
会话控制器
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to current_user
else
flash.now[:error] = "There was a problem authenticating."
render action: 'new'
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Signed out!"
end
应用程序控制器
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
end
helper_method :current_user
答案 0 :(得分:1)
注册后,您创建了用户,但没有创建会话。当您查找current_user时,会话[:user_id]没有值。
另外,我认为current_user方法可能对模型不可见。
您可以尝试这样的事情:
class UsersController < ApplicationController
before_action :set_user, only: [:show]
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "Welcome to the site"
session[:user_id] = @user.id # <=====
redirect_to @user # <=====
else
flash[:notice] = "There was a problem creating your account. Please try again."
render new
end
end
...
end
答案 1 :(得分:0)
你需要
保存新用户后重定向前的session[:user_id] = user.id
。您未设置它,因此创建用户时session[:user_id]
为零