【问题标题】:omniauth-facebook error email has already been takenomn​​iauth-facebook 错误电子邮件已被接收
【发布时间】:2017-08-10 14:27:31
【问题描述】:

美好的一天,我是新来的 ruby​​ on rails。我正在开发一个旅游应用程序,我想提供使用 facebook 登录的选项。实际上,我的应用程序在使用 facebook 注册时运行良好,但是当我关闭会话并且尝试再次使用 facebook 登录时出现错误,它显示“电子邮件已被占用”有人可以帮忙吗?我会感谢你的帮助。

user.rb

class User < ApplicationRecord

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable       
  devise :omniauthable, omniauth_providers: [:facebook]

  has_many :destinations
  has_many :deals
  has_many :payments
  has_many :transactions
  has_many :questions
  has_many :comments

def self.find_or_create_by_omniauth(auth)
    user = User.find_by(provider: 'provider', uid: ':uid')

    unless user
      user = User.create(
          name: auth[:name],
          last_name: auth[:last_name],
          nickname: auth[:nickname],
          email: auth[:email],
          uid: auth[:uid],
          provider: auth[:provider],
          password: Devise.friendly_token[0,20]
        )
    end
    user
  end
end

routes.rb

Rails.application.routes.draw do

 devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}
end

omniauth_callbacks_controller.rb

class OmniauthCallbacksController < ApplicationController
    def facebook
        auth = request.env["omniauth.auth"]

        data = {
            name: auth.info.first_name,
            last_name: auth.info.last_name,
            nickname: auth.info.nickname,
            email: auth.info.email,
            provider: auth.provider,
            uid: auth.uid
        }

        @user = User.find_or_create_by_omniauth(data)

        if @user.persisted?
            sign_in_and_redirect @user, event: :authentication
        else
            session[:omniauth_errors] = @user.errors.full_messages.to_sentence unless @user.save

            session[:omniauth_data] = data


            redirect_to new_user_registration_url
        end
    end
end

缺少什么?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    更改以下行

    user = User.find_by(provider: 'provider', uid: ':uid')
    

    user = User.find_by(provider: auth[:provider], uid: auth[:uid])
    

    或为了进一步简化方法,请在下面使用

    def self.find_or_create_by_omniauth(auth) # I recommend using a better name for this method instead of find_or_create_by as it looks like query
      where(provider: auth[:provider], uid: auth[:uid]).first_or_create do |user|
        name: auth[:name],
        last_name: auth[:last_name],
        nickname: auth[:nickname],
        email: auth[:email],
        uid: auth[:uid],
        provider: auth[:provider],
        password: Devise.friendly_token[0,20]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多