2015-08-27 38 views
0

這就是我的OmniauthCallbacksController的樣子。我爲這裏的FB登錄設置會話[:user_id],它工作正常。爲什麼在使用設計註冊後會話[:user_id]爲空?

class SessionsController < Devise::OmniauthCallbacksController 
    def facebook 
    @user = User.from_omniauth(request.env["omniauth.auth"]) 

    if @user.persisted? 
     session[:user_id] = @user.id 
     line #9 
     sign_in_and_redirect @user , :event => :authentication #this will throw if @user is not activated 
     set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format? 
    else 
     session["devise.facebook_data"] = request.env["omniauth.auth"] 
     redirect_to new_user_registration_url 
    end 
    end 

    def destroy 
    session[:user_id] = nil 
    redirect_to root_url 
    end 
end 

class ApplicationController < ActionController::Base 

    protect_from_forgery with: :exception 



    # uncomment this block if I want to set session after a sign up through devise. 
    # def after_sign_in_path_for(resource) 
    # session[:user_id] = resource.id 
    # end 



def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    end 

問題是,當我取消註釋代碼塊以上,註冊窗口工作色器件,但我得到以下錯誤,當我試圖通過Facebook註冊,我碰到下面的錯誤。

NoMethodError (undefined method `to_model' for 2:Fixnum): 
    app/controllers/sessions_controller.rb:9:in `facebook' 

我該如何讓這兩者合作?

回答

0

after_sign_in_path_for應該返回一個URL或資源

sign_in_and_redirect將使用URL /資源重定向頁面

我們可以更新方法:

def after_sign_in_path_for(resource) 
    session[:user_id] = resource.id 
    root_path 
end 
+0

我只是通過刪除解決的問題我明確定義的current_user方法。我想因爲omniauth是在devise.rb中配置的,所以我不應該定義currenta_user。讓我知道你的想法。 – user2441151

+0

是的,已經定義了'current_user'。我只是在使用'after_sign_in_path_for'的時候提出一些意見,以防你需要它:) –