在我的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 ...
清楚地初始化了一个用户对象管理此步骤的代码如下:
Session#create controller
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 ...
答案 0 :(得分:0)
我不认为find_by_provider_and_uid
设置了用户属性,因此如果成功,则需要考虑到这一点。
auth = find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])
if auth.nil? # i don't know if nil is the right condition to check for, my active record fu is not up to date.
# do your unless code
else
#need to fetch and set user property
end
auth
答案 1 :(得分:0)
用户可能无法通过验证,实际上并未创建。将User.create
更改为User.create!
,如果验证失败,您会立即看到,因为它会引发异常。