2012-12-29 81 views
2

我使用devise並試圖下一以下:錯誤:重定向過多

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    before_filter :is_worker 

    def is_worker 
    if user_signed_in? 
     @email = current_user.email 
     if @email && Worker.find_by_email(@email).nil? 
      redirect_to '/tasksadmins' 
     else 
      redirect_to '/workers' 
     end 
    else 
     redirect_to '/users/sign_in' 
    end 
    end 
end 

當我試圖進入現場:localhost:3000/tasksadmins,我得到:

Oops! It was not possible to show this website 

The website at http://localhost:3000/tasksadmins seems to be unavailable. The precise error was: 

Too many redirects 

It could be temporarily switched off or moved to a new address. Don't forget to check that your internet connection is working correctly. 

如何解決好嗎?

回答

5

before_filter適用於每一個請求。這就是爲什麼它一次又一次地重定向。

你可能只想過濾特定的動作:

before_filter :is_worker, only: :index 

另一種解決辦法是請檢查是否重定向是必要的,#is_worker

redirect_to '/workers' unless request.fullpath == '/workers' 

編輯:

另一個方法是跳過之前的過濾器以實現重定向的目標操作。例如:

class WorkersController < ApplicationController 

    skip_before_filter :is_worker, only: :index 

    # … 

end 
+0

我試過你的第一個解決方案,並且出現錯誤:http:// localhost:3000/workers的網站似乎不可用。確切的錯誤是: 重定向過多 –

+0

這是因爲您正在重定向到'工作人員'控制器的'索引'動作。而不是我的第一個解決方案:在你的'WorkersController'中,你可以調用'skip_before_filter:is_worker,只有:: index',這樣重定向發送到處,但不是'/ workers'。你可以對'/ tasksadmins'和'/ users/sign_in'應用相同的值。 – Koraktor

+0

謝謝..我正在嘗試:] –