2010-11-14 66 views
14

在我的應用程序中,我使用Devise對用戶進行了身份驗證,並且我注意到如果登錄失敗,您可以更改重定向到的頁面。在維基我發現下面的例子:當用戶無法使用Devise登錄時重定向問題

class CustomFailure < Devise::FailureApp 
    def redirect_url 
    new_user_session_url(:subdomain => 'secure') 
    end 

    # You need to override respond to eliminate recall 
    def respond 
    if http_auth? 
     http_auth 
    else 
     redirect 
    end 
    end 
end 

下面這個例子我創建了自己CustomFailure類(custom_failure.rb),並放置在幫助文件夾(不知道在哪裏把它)。這是下面的類我創建:

class CustomFailure < Devise::FailureApp 
    def redirect_url 
    new_user_session_url(:subdomain => 'secure') 
    end 

    # Redirect to root_url 
    def respond 
    if http_auth? 
     http_auth 
    else 
     root_url 
    end 
    end 
end 

我還添加在config /初始化/ devise.rb文件中的以下(如維基國應該做的):

config.warden do |manager| 
    manager.failure_app = CustomFailure 
end 

雖然我得到沒有錯誤,當我錯誤地登錄它仍然重定向到/ users/sign_in頁面(而不是根頁面)並且沒有被加載(即使源不是空的,頁面也是完全白色的)。我的CustomFailure類有錯,或者它在錯誤的文件夾中?

我正在使用Rails 3.0.1和Devise 1.1.rc0。

哪裏這段代碼中發現的維基是:How To: Redirect to a specific page when the user can not be authenticated

回答

19

嘗試把custom_failure.rb到您lib文件夾,因爲它不是一個幫手。然後確保文件已加載。可能您會嘗試自動加載lib中的所有文件。

編輯:要實現加載lib目錄自動將插入以下到您的application.rb

config.autoload_paths += %W(#{config.root}/lib) 

EDIT2:你忘了嘗試重定向何時調用redirect_to。目前respond只返回root_url。 FYI

def respond 
    if http_auth? 
    http_auth 
    else 
    redirect_to root_url 
    end 
end 

:嘗試這個色器件-傢伙重定向之前也執行此:

store_location! 
flash[:alert] = i18n_message unless flash[:notice] 
+0

嗯並沒有工作。它只是做了同樣的事情。 – Fizz 2010-11-16 02:34:28

+0

我重新思考你的問題。試試我的另一種方法 - 希望這會有所幫助! – pex 2010-11-16 03:10:51

+0

非常感謝你。有用!我沒有添加store_location!在重定向之前,我應該在我的「其他」條款中這麼做嗎? – Fizz 2010-11-16 04:20:53