尝试使用google_oauth2 gem登录google +时出现以下错误。
undefined method `find_for_google_oauth2' for #<Class:0x007ff70a337148>
这是我为注册而更改的三个文件。
user.rb
def google_oauth2
user = User.from_omniauth(request.env["omniauth.auth"])
if user.persisted?
flash.notice = "Signed in Through Google!"
sign_in_and_redirect user
else
session["devise.user_attributes"] = user.attributes
flash.notice = "You are almost Done! Please provide a password to finish setting up your account"
redirect_to new_user_registration_url
end
end
omniauth_callbacks_controller.rb
def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
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"]
redirect_to new_user_registration_url
end
end
我在devise.rb文件中添加了config.omniauth:google_oauth2。
的routes.rb
devise_for :users, :controllers => { :registrations => "registrations", :sessions => "sessions", :omniauth_callbacks => "users/omniauth_callbacks" }
答案 0 :(得分:1)
您正在从find_for_google_oauth2
拨打omniauth_callbacks_controller
,但您使用的是错误的方法名称google_oauth2
。您应该将google_oauth2
替换为find_for_google_oauth2
。
似乎user.rb
中的代码不正确,因为它包含控制器代码。您是否看到它与控制器代码完全相同? :)
更正user.rb的代码
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
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
在此处阅读更多内容:https://github.com/zquestz/omniauth-google-oauth2#devise