rails5 + deviseでomniauthableを使っており、google_oauth2でnameとemailを取得したいのですが、emailは問題なくできますが、nameが取れずに代わりにemailの情報がnameのカラムに入ってしまいます。
下記のコードをご覧いただき、どこが間違っているか教えていただけると幸いです。
よろしくお願いいたします。
user.rb
ruby
1class User < ApplicationRecord 2 devise :database_authenticatable, :registerable, :confirmable, :lockable, 3 :recoverable, :rememberable, :trackable, :validatable, :timeoutable, 4 :omniauthable, omniauth_providers: [:facebook, :twitter, :google_oauth2] 5 6 def self.find_for_google_oauth2(auth) 7 user = User.where(email: auth.info.email).first 8 unless user 9 user = User.new(name: auth.info.name, 10 provider: auth.provider, 11 uid: auth.uid, 12 email: auth.info.email, 13 token: auth.credentials.token, 14 password: Devise.friendly_token[0, 20]) 15 user.skip_confirmation! 16 user.save 17 end 18 user 19 end 20 21 def self.from_omniauth(auth) 22 where(provider: auth.provider, uid: auth.uid).first_or_create do |user| 23 user.email = auth.info.email 24 user.password = Devise.friendly_token[0,20] 25 user.name = auth.info.name # assuming the user model has a name 26 #user.image = auth.info.image # assuming the user model has an image 27 # If you are using confirmable and the provider(s) you use validate emails, 28 # uncomment the line below to skip the confirmation emails. 29 user.skip_confirmation! 30 end 31 end 32 33end
omniauth_callbacks_controller.rb
ruby
1class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController 2 3 def google_oauth2 4 @user = User.find_for_google_oauth2(request.env["omniauth.auth"]) 5 if @user.persisted? 6 sign_in_and_redirect @user, event: :authentication 7 set_flash_message(:notice, :success, kind: "Google") if is_navigational_format? 8 else 9 session["devise.google_data"] = request.env["omniauth.auth"] 10 redirect_to new_user_registration_url 11 end 12 end 13 14end
あなたの回答
tips
プレビュー