在我的 Rails 应用程序中,我正在执行以下步骤:
用户需要登录 -> 用户创建授权 -> 用户创建
该应用程序似乎在该过程的最后一步出现问题。
我成功创建授权:
Authorization Load (0.9ms) SELECT "authorizations".* FROM "authorizations" WHERE "authorizations"."provider" = 'facebook' AND "authorizations"."uid" = '2259711' LIMIT 1
Authorization attributes hash: {"id"=>1, "uid"=>"2259711", "provider"=>"facebook", "user_id"=>1, "created_at"=>Wed, 02 May 2012 06:06:13 UTC +00:00, "updated_at"=>Wed, 02 May 2012 06:06:13 UTC +00:00}
但它随后在用户创建步骤中窒息:
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Completed 500 Internal Server Error in 26ms
RuntimeError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):
app/controllers/sessions_controller.rb:21:in `create'
会话控制器的第 21 行是这样的:session[:user_id] = @auth.user.id
然而这没有任何意义,因为我已经清楚地用正确的 id 初始化了一个用户对象......
控制此步骤的代码如下:
会话#创建控制器
def create
# create the auth hash here
auth_hash = request.env['omniauth.auth']
if session[:user_id]
# Means our user is signed in. Add the authorization to the user
User.find(session[:user_id]).add_provider(auth_hash)
redirect_back_or User.find(session[:user_id])
# render :text => "You can now login using #{auth_hash["provider"].capitalize} too!"
else
# Log him in or sign him up
@auth = Authorization.find_or_create(auth_hash)
# Create the session
logger.debug "Person attributes hash: #{@auth.attributes.inspect}"
session[:user_id] = @auth.user.id
# render :text => "Welcome #{auth.user.name}!"
sign_in @auth.user
redirect_back_or @auth.user
end
end
授权 find_or_create 模型方法
def self.find_or_create(auth_hash)
unless auth = find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])
user = User.create :name => auth_hash["info"]["name"], :email => auth_hash["info"]["email"]
logger.debug "Within Authorization find_or_create: Person attributes hash: #{user.attributes.inspect}"
auth = create :user => user, :provider => auth_hash["provider"], :uid => auth_hash["uid"]
end
auth
end
更新
当我尝试这个时:logger.debug "User attributes hash: #{@auth.user.attributes.inspect}"
在上面的会话控制器中,我收到了这个错误:
NoMethodError (undefined method `attributes' for nil:NilClass):
app/controllers/sessions_controller.rb:21:in `create'
这意味着用户对象为零。这不应该是这种情况,因为我在授权find_or_create
方法中调用了 user.create ......