class SessionsController < ApplicationController
def create
auth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"],auth["uid"]) ||
User.create_with_omniauth(auth)
session[:user_id]=user.id
redirect_to("/sessions/sign")
end
def sign
end
end
这是用户模型
class User < ActiveRecord::Base
attr_accessible :name, :provider, :uid
def self.create_with_omniauth(auth)
create! do |user|
user.provider=auth["provider"]
user.uid=auth["uid"]
user.name=auth["user_info"]["name"]
end
end
end
错误:
undefined method '[]' for nil:NilClass
当我通过Facebook登录时,我收到上述错误
答案 0 :(得分:2)
您需要确保以下内容存在且不是nil
auth = request.env["omniauth.auth"]
你可以做到
auth = request.env["omniauth.auth"]
if auth
# do stuff
else
# error handler
end
或者在你的模特中我会检查:
def self.create_with_omniauth(auth)
return unless auth
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["user_info"]["name"]
end
end
最后,您可以使用try
方法处理nil
值,如下所示:
auth.try(:[], 'provider')
如果auth
为nil
,则会返回nil
,否则会返回包含密钥provider