2012-09-01 75 views
1

我得到未定義的方法`[]」的零:NilClassNoMethodError在用戶:: OmniauthCallbacksController#Facebook的

NoMethodError in Users::OmniauthCallbacksController#facebook 

    undefined method `[]' for nil:NilClass 

    Rails.root: /home/krishna/picer 
    Application Trace | Framework Trace | Full Trace 

    app/models/user.rb:13:in `find_for_facebook_oauth' 
    app/controllers/users/omniauth_callbacks_controller.rb:4:in `facebook' 

這是我user.rb代碼

class User < ActiveRecord::Base 
# Include default devise modules. Others available are: 
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable:omniauthable 
devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable, 
    :omniauthable 

# Setup accessible (or protected) attributes for your model 
attr_accessible :email, :password, :password_confirmation, :remember_me 

def self.find_for_facebook_oauth(access_token, signed_in_resource=nil) 
data = access_token['extra']['user_hash'] 
if user = User.find_by_email(data["email"]) 
    user 
else # Create a user with a stub password. 
    User.create(:email => data["email"], :password => Devise.friendly_token[0,20]) 
    end 
end 

def self.new_with_session(params, session) 
    super.tap do |user| 
    if data = session["devise.facebook_data"] && session["devise.facebook_data"] ["extra"]["user_hash"] 
    user.email = data["email"] 
    end 
    end 
end 
end 

而且omniauth回調控制器代碼

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController 
def facebook 
# You need to implement the method below in your model 
@user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user) 

if @user.persisted? 
    flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook" 
    sign_in_and_redirect @user, :event => :authentication 
else 
    session["devise.facebook_data"] = env["omniauth.auth"] 
    redirect_to new_user_registration_url 
end 
end 

def passthru 
    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false 
end 

end 

我收到錯誤四個user.rb我用一個例子此https://github.com/ryanatwork/devise-omniauth

+0

access_token ['extra'] ['user_hash']可能是零,你可以登錄到控制檯嗎? –

回答

1

您應該收到access_token['info']['email']而不是access_token['extra']['user_hash']['email']的用戶電子郵件。

我不認爲access_token['extra']中的數據遵循其他規則,因此您應該特別小心並測試您嘗試訪問的屬性是否存在。如果你只有一個提供者,這並不重要,但如果你有幾個提供者,那就沒有那麼重要了。

相關問題