设计的##sign_in_and_redirect`会使用户持久,即使无效

时间:2014-04-01 18:56:08

标签: ruby-on-rails devise omniauth

使用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
...

1 个答案:

答案 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