2016-12-06 16 views
0

Google、Linkedin、DropboxおよびGithubを使用して、デバイスの上にさらに簡単なソーシャルユーザー認証をセットアップしました。

のDropbox認証ではなく、それがコールバックURL
http://localhost:3000/users/auth/dropbox/callback)にそのエラーを与え、機能しません。Rails 4:ユーザー認証 - NoMethodError

NoMethodError in Users::OmniauthCallbacksController#dropbox 
undefined method `first' for nil:NilClass 

問題:ユーザーモデル(ライン8)


マイコード:

コールバックコントローラ:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController 

    def all 
     user = User.from_omniauth(env['omniauth.auth'], current_user) 
     if user.persisted? 
      sign_in user 
      flash[:notice] = t('devise.omniauth_callbacks.success', :kind => User::SOCIALS[params[:action].to_sym]) 
      if user.sign_in_count == 1 
       redirect_to edit_user_registration_path 
      else 
       redirect_to root_path 
      end 
     else 
      session['devise.user_attributes'] = user.attributes 
      redirect_to new_user_registration_url 
     end 
    end 

    User::SOCIALS.each do |k, _| 
     alias_method k, :all 
    end 

end 

ユーザーモデル:

# omniauth Gem 
def self.from_omniauth(auth, current_user) 
    authorization = Authorization.where(:provider => auth.provider, :uid => auth.uid.to_s, 
             :token => auth.credentials.token, 
             :secret => auth.credentials.secret).first_or_initialize 
    authorization.profile_page = auth.info.urls.first.last unless authorization.persisted? 
    if authorization.user.blank? 
     user = current_user.nil? ? User.where('email = ?', auth['info']['email']).first : current_user 
     if user.blank? 
      user = User.new 
      user.skip_confirmation! 
      user.password = Devise.friendly_token[0, 20] 
      user.fetch_details(auth) 
      user.save 
     end 
     authorization.user = user 
     authorization.save 
    end 
    authorization.user 
end 

def fetch_details(auth) 
    self.email = auth.info.email 
    self.username = auth.info.name 
    self.avatar = URI.parse(auth.info.image) 
end 

私はそれぞれの助けに感謝!前もって感謝します。

答えて

1

ご質問に直接お答えください: firstを空またはnilオブジェクトに呼び出すと、undefined method "first" for nil::NilClassが起きています。

これは、現在のユーザーからcurrent_userのユーザーを探している可能性があります。

if authorization.user.blank? user = current_user.nil? ? User.where('email = ?', auth['info']['email']).first : current_user #This will cause the error that you are describing if both the current_user is nil and there is no User whose email is auth['info']['email']

さて、これで間違っている点がいくつかあります。アプリケーションにログインしようとしている場合は、この段階のcurrent_userを設定解除する必要があります。

あなたは1つが認証で提供メールで存在しない場合は、ユーザーの新しいインスタンスを作成します

user = User.where(email: auth['info']['email']).first_or_create

にこれを変更してみてください。 そして、あなたは、私はエラーが後に持続しているため問題は、Userモデルの5行目にあると思い

既存のユーザーのためにtrueを返します

user.persisted? 、およびユーザー

+0

の新しいインスタンスのための偽のを続行することができます私はあなたの提案を取り入れました。それはDropboxのように、それは何とかURLを見つけることができないようです。 – jonhue

+0

したがって、同じ原則が適用されます。 'auth.info.urls'で' .first'を呼んでいます。これは空であるか存在しないことを意味します。この行の直前でプログラムを停止し、authが実際に戻っているものを確認し、それに応じてコードを整形するには、pryまたはbyebugを使用してデバッグします。 –

関連する問題