2016-04-22 67 views
1

雖然試圖在我的Rails應用程序中實現Omniauth-twitter,但我遇到了上述錯誤。 該錯誤集中在我的控制器中的一個聲明,我知道它與twitter沒有提供回調電子郵件有關。我正在使用設計進行身份驗證。我也打算安裝Facebook omniauth,但希望讓Twitter先工作。 我可以實現哪些代碼塊來跳過Twitter的驗證?它是否在我的控制器或用戶模型?OmniauthCallbacksController中的ActiveRecord :: RecordInvalid#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 
+0

你確定'@details [「info」] [「email」]'這不是零或什麼? – Rashmirathi

+0

不需要。它需要超出此驗證範圍,以便回調起作用。 –

+0

':validatable'是驗證「email」存在的東西。所以你可能會刪除':validatable'和你自己的驗證。在這裏看到https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb – Rashmirathi

回答

0

我找到了答案與此公司行de在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!