OmniauthCallbacksController中的ActiveRecord :: RecordInvalid #tube验证失败:电子邮件不能为空

时间:2016-04-22 13:23:46

标签: ruby-on-rails activerecord twitter devise omniauth

虽然尝试将Omniauth-twitter实施到我的Rails应用程序中,但我遇到了上述错误。 错误集中在我的控制器中的一个语句中,我理解这与twitter在回调时不提供电子邮件有关。我正在使用设计进行身份验证。我还打算安装Facebook omniauth,但希望让Twitter首先运作。 我可以实现哪些代码块来跳过Twitter的验证?它是否属于我的控制器或用户模型?

这是我的代码 -

OmniauthCallbacksController -

class OmniauthCallbacksController < Devise::OmniauthCallbacksController

def twitter

     @details = request.env["omniauth.auth"]

    @provider = @details["provider"]
    @provider_id = @details["uid"]

    @user = User.where(provider: @provider, provider_id: @provider_id).first

    if @user.present?
        #sign them in
    else
        # make a new user
        @user = User.new
        @user.provider = @provider
        @user.provider_id = @provider_id

        # because of has_secure_password - will this work?
        @user.password = "AAAAAA!!"
        @user.password_confirmation = "AAAAAA!!"

        # let's save the key and secret
        @user.key = @details["credentials"]["token"]
        @user.secret = @details["credentials"]["secret"]

        # lets fill in their details
        @user.name = @details["info"]["name"]
        @user.email = @details["info"]["email"]

        @user.save!
    end


        session[:uid] = @user.id 
        flash[:success] = "You've logged in"
        redirect_to root_path

end

def password_required?
    super && provider.blank?
end






end

routes.rb

Rails.application.routes.draw do

  #get "/auth/:provider/callback" => "social_logins#create"


  devise_for :users, :controllers => { omniauth_callbacks:     "omniauth_callbacks", registrations: 'registrations' }  



  resources :users
  resources :events do

    resources :bookings
  end
  # get 'welcome/index'


  authenticated :user do
    root 'events#index', as: "authenticated_root"
  end


    root 'welcome#index'




end

User.rb

class User < ActiveRecord::Base

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

         has_many :events
         has_many :bookings
         has_many :authentications




end

1 个答案:

答案 0 :(得分:0)

我在OmniauthCallbackController中找到了这行代码的答案

  # lets fill in their details
        @user.name = @details["info"]["name"]
        if @provider == "twitter"? @user.save!(:validate => false) : @user.save!
        # the above if statement allows for twitter to skip validation which requires an email
        @user.email = @details["info"]["email"]
        end

        @user.save!