2016-08-16 72 views
0

我試圖讓用戶通過Twitter登錄,但出現錯誤:在SessionsController中輸入錯誤。每當我重定向到https://api.twitter.com/oauth/authenticate時,都會收到此錯誤,以便用戶可以進行身份​​驗證。在進行身份驗證後,我應該重定向到Twitter「Authorize App」頁面,但是我收到了完整的錯誤:「SessionsController中的TypeError#create:exception class/object expected」。我正在使用omniauth_twitter併爲此功能設計寶石。我是否錯過了我需要在routes.rb文件中設計的東西?SessionsController中的TypeError#嘗試使用omniauth從Twitter API登錄用戶時創建

此外,它通過創建方法(在SessionController中),因爲它最終會重定向到根頁面,但我看不到在數據庫中創建的用戶。

會話控制器

class SessionsController < ApplicationController 

def create 
    @user = User.find_or_create_from_auth_hash(auth_hash) 
    session[:user_id] = @user.id 
    redirect_to root_path 
end 

protected 

def auth_hash 
    request.env['omniauth.auth'] 
end 
end 

用戶模型

class User < ActiveRecord::Base 
devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 

before_create :generate_auth_token 

def self.find_or_create_from_auth_hash(auth_hash) 
user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create 
user.update(
    name: auth_hash.info.name, 
    avatar: auth_hash.info.image, 
    token: auth_hash.credentials.token, 
    secret: auth_hash.credentials.secret) 
user 
end 

def generate_auth_token 
loop do 
    self.auth_token = SecureRandom.base64(64) 
    break unless User.find_by(auth_token) 
end 
end 
end 

的routes.rb

Rails.application.routes.draw do 
    get 'auth/:provider/callback', to: 'sessions#create' 

    resources :tweets 

    get 'signup/new' 

    get 'signup/create' 


    devise_for :users 


    resources :contacts 
    end 

另外,用戶沒有在數據庫中顯示它應該被保存下來

Loading production environment (Rails 4.2.1) 
[1] pry(main)> User.all 
User Load (3.2ms) SELECT "users".* FROM "users" 
=> [] 

回答

0

你會看到這個錯誤,因爲1)你在養#SessionsController異常創建(raise :test)和2)raise是不期待一個符號,這就是爲什麼你看到那個神祕的錯誤信息。

λ irb 
2.3.1 :001 > raise :test 
TypeError: exception class/object expected 
     from (irb):1:in `raise' 
     from (irb):1 
     from /home/peter/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>' 

您應該刪除通話提高,如果它實際上並不應該在那裏或者,如果是,請撥打raise有一個合法的參數(字符串,異常實例等),並相應rescue

+0

感謝您的回覆。是的,我早些時候嘗試過,把它拿出來,它仍然沒有將用戶存入數據庫。當我進入導軌控制檯時,我甚至沒有看到我的用戶模型中的用戶: 加載生產環境(Rails 4.2.1) [1] pry(main)> User.all User Load(3.2ms )SELECT「users」。* FROM「users」 => [] – SaintClaire33

+0

這可能與Devise有什麼關係嗎? – SaintClaire33

+0

我還沒有被重定向到Twitter的授權應用頁面。任何人都可以擺脫光線嗎? – SaintClaire33

相關問題