Omniauth 不工作:未定义的方法“持续存在?” nil:NilClass

Omniauth not working: undefined method `persisted?' for nil:NilClass

Error Message Picture

我基本上完全按照下面的说明进行操作 link,但我却遇到了这个该死的错误?我不知道我应该做什么,wtf?我需要创建某种持久化方法吗??还有其他几个类似的问题,在阅读所有这些问题后,它们根本没有帮助。请帮忙。

https://github.com/zquestz/omniauth-google-oauth2

Omniauths 控制器

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
  # You need to implement the method below in your model (e.g. app/models/user.rb)
  @user = User.from_omniauth(request.env["omniauth.auth"])

  if @user.persisted?
    flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
    sign_in_and_redirect @user, :event => :authentication
  else
    session["devise.google_data"] = request.env["omniauth.auth"].except(:extra) #Removing extra as it can overflow some session stores
    redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
  end
  end
end

用户模型代码片段

def self.from_omniauth(access_token)
data = access_token.info
user = User.where(:email => data["email"]).first
# Uncomment the section below if you want users to be created if they don't exist
# unless user
#     user = User.create(name: data["name"],
#        email: data["email"],
#        password: Devise.friendly_token[0,20]
#     )
# end
  user
end

将底部更改为:

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.name = auth.info.name   # assuming the user model has a name
 end
end

运行 rails g 迁移 AddOmniauthToUsers provider:string uid:string

然后它从 Google 帐户成功验证。

所以我相信它现在可以工作了。我想问题可能是我需要将提供程序和 uid 添加到用户数据库模型?

坚持了?方法正在检查用户是否存在,如果不存在这样的记录并且您的用户模型没有创建新的,则返回 nil 值。因此,通过取消注释示例中的代码:

def self.from_omniauth(access_token)
  data = access_token.info
  user = User.where(:email => data["email"]).first

  # creates a new user if user email does not exist.
  unless user
    user = User.create(name: data["name"],
       email: data["email"],
       password: Devise.friendly_token[0,20]
    )
  end
 user
end

应该解决检查用户是否存在或创建新用户的问题。