Omniauth不工作:未定义的方法`坚持?'为零:NilClass

时间:2017-05-24 22:22:40

标签: ruby-on-rails omniauth-google-oauth2

Error Message Picture

我基本上完全按照以下链接中的说明操作,我得到了这个该死的错误?我不知道我应该做什么,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

2 个答案:

答案 0 :(得分:2)

将底部部分更改为:

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 migration AddOmniauthToUsers提供者:string uid:string

然后,它从Google帐户成功通过身份验证。

所以我相信它现在有效。我想问题可能是我需要将提供者和uid添加到用户数据库模型中吗?

答案 1 :(得分:0)

坚持不懈?方法正在检查用户是否存在,如果不存在这样的记录并且您的用户模型没有创建新记录,则返回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

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