2013-04-11 91 views
0

我正在使用Omniauth尝试在我的Web应用程序上注册/登录用户。 这是我AuthenticationsController#Create方法内发生的事情:NoMethodError - 未定义的方法`user'for nil:NilClass

认证控制器:

class AuthenticationsController < InheritedResources::Base 

    def create 
    omniauth = request.env['omniauth.auth'] 
    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) 
    if authentication 
     flash[:success] = "Signed in successfully" 
     sign_in_and_redirect(authentication.user) 
    elsif current_user 
     token = omniauth['credentials'].token 
     secret = omniauth['credentials'].secret 
     current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => token, :secret => token_secret) 
     flash[:success] = "Authentication successful" 
     redirect_to authentications_url 
    else 
     user = User.new 
     user.apply_omniauth(omniauth) 
     if user.save! 
     flash[:success] = "Account created" 
     sign_in(authentication.user) 
     else 
     session[:omniauth] = omniauth.except('extra') 
     redirect_to '/signup' 
     end 
    end 
    end 

我本来sign_in(:user, authentication.user),但它给了我的说法的错误,所以我改成了刚刚在上面的代码had sign_in(authentication.user)。但是,现在我得到NoMethodError - undefined method 'user' for nil:NilClass

回答

0

首先测试authentication是否定义,然后在else块中,如果它没有定义,它将只触发,你去参考authentication.user出于某种原因。这不可能工作。

如果您未通过身份验证并且未登录,那么该条件似乎适用。您为什么要在这些情况下使用sign_in函数?

+0

该控制器的正确“def创建”应该是什么样子?我试图按照Railscast for omniauth – user2159586 2013-04-11 05:37:40

1

第23行sign_in(authentication.user)由于您处于if authentication条件的else分支(因此authentication为零)而失败。 您可能打算做的事情是拨打sign_in(user),您只需在上面创建几行即可。

+0

我将其更改为'sign_in_and_redirect(user)',但我仍然得到未定义的局部变量或方法'user' – user2159586 2013-04-11 05:36:40

0

如果您使用您的数据库供应商的一组列表确保

> :provider => omniauth['provider'] 

与在数据库供应商相匹配,例如。如果你的数据库中有facebook_Oauth2,并且提供者的响应是facebook,那么保证会失败。

相关问题