0

我正在使用omniauth facebook gem 设置设计来构建注册系统。用户可以使用电子邮件注册或连接他们的 Facebook 帐户。如果电子邮件注册用户使用 facebook 帐户登录,我检查电子邮件地址是否已注册并连接这两个帐户,然后登录用户。

这整个场景已经奏效了。用户条目将使用 facebook 的新omniauth 数据进行更新。当 facebooks 发送回调(来自 facebook 的数据成功保存到 db)时,我收到此错误:

CallbacksController#facebook 中的 RuntimeError

找不到 true 的有效映射

提取的源代码(第 5 行附近):

class CallbacksController < Devise::OmniauthCallbacksController
  # Define each provider for omniauth here (def twitter...)
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
    sign_in_and_redirect @user
  end
end

user.rb 模型看起来像这样:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook]

  def self.from_omniauth(auth)
    user = where(provider: auth.provider, uid: auth.uid).first
    unless user
      user = where(email: auth.info.email).first_or_initialize
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email
      user.name = auth.info.name
      user.nickname = auth.info.nickname
      user.first_name = auth.info.first_name
      user.last_name = auth.info.last_name
      user.location = auth.info.location
      user.description = auth.info.description
      user.image = auth.info.image
      user.phone = auth.info.phone
      user.urls = auth.info.urls
      user.password = Devise.friendly_token[0,20]
      user.save!
    end
  end
end

路线.rb

Rails.application.routes.draw do
  devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }
  resources :auctions do
    resources :comments
  end

  root 'welcome#index'
  get '/', :to => 'welcome#index'
end
4

1 回答 1

1

self.from_omniauthUser班级中的方法正在返回true,而不是User模型。这是因为 Ruby 中方法的返回值是最后一行的结果,在这种情况下user.save!是运行的最后一行。“Could not find a valid mapping for true”错误是true传入sign_in_and_redirect; 您可以在 Devise 源代码中看到第一个参数被传递到Devise::Mapping.find_scope!.

解决方案很简单 - 确保您在以下位置返回user模型from_omniauth

def self.from_omniauth(auth)
    user = where(provider: auth.provider, uid: auth.uid).first
    unless user
      user = where(email: auth.info.email).first_or_initialize
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email
      user.name = auth.info.name
      user.nickname = auth.info.nickname
      user.first_name = auth.info.first_name
      user.last_name = auth.info.last_name
      user.location = auth.info.location
      user.description = auth.info.description
      user.image = auth.info.image
      user.phone = auth.info.phone
      user.urls = auth.info.urls
      user.password = Devise.friendly_token[0,20]
      user.save!
    end
    user # Make sure we return the user we constructed.
  end
于 2015-09-11T04:19:31.710 回答