2014-12-10 53 views
1

我遇到了我的導軌身份驗證問題。我沒有使用Devise。無論出於何種原因,當我登錄到應用程序時,一切都很好,但是當我在創建新帳戶時嘗試重定向時,current_user爲零?有什麼建議?Rails 4用戶認證從零開始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" 
     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

在剛剛創建的用戶create操作,從而沒有對這一請求沒有CURRENT_USER呢。只需'redirect_to @ user' – 2014-12-10 23:03:47

回答

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 
+0

這就是完美的@roob。我在對用戶進行身份驗證後分配了會話[:user_id],但在創建之後未分配該會話。謝謝! – 2014-12-11 15:35:43

0

您會在儲存新用戶後需要重定向之前 session[:user_id] = user.id。您尚未設置session[:user_id]當您創建用戶時爲零