使用Omiseuth Github策略与Devise with Rails 4。
我的验证失败导致下面代码中的#create失败(返回失败的User对象并输入if
,因为它仍然评估为true
)并且未持久化然后将用户传递给#sign_in_and_redirect
(模型错误完好无损)。直到这里,我对一切都很满意。代码不好,但在有意义的方面很糟糕。
尽管如此,用户在#sign_in_and_redirect
代码中的某处实际创建(通过使用描述性puts
和服务器日志缩小它来发现)。
A)我找不到发生在Devise或Omniauth源中的位置。我找不到#save
或#create
来电。
B)即使#create
调用了#save
或#sign_in_and_redirect
,它们仍然会因错误而失败。
这怎么可能?!
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
...
user = User.create(provider: omniauth['provider'],
uid: omniauth['uid'],
email: omniauth['info']['email'],
username: omniauth['info']['nickname'])
if user
flash.now[:notice] = "Signed in successfully"
# Makes perfect sense how we got here, user is currently not persisted
sign_in_and_redirect(:user, user)
# Somehow, magically, user is now persisted
else
...
答案 0 :(得分:0)
在给定代码中虽然用户由于验证错误而未创建,但user
仍然不是false
。它实际上是一个带有验证错误的用户对象对象。因此,如果您想检查添加用户创建的条件,那么您应首先构建user
对象,然后在其上调用save
。
user = User.new(provider: omniauth['provider'],
uid: omniauth['uid'],
email: omniauth['info']['email'],
username: omniauth['info']['nickname'])
# user.save will return a boolean value.
if user.save
flash.now[:notice] = "Signed in successfully"
sign_in_and_redirect(:user, user)
else
...
end