2011-07-01 23 views
2

我想將用戶重定向如果條件爲真:的Rails:重定向到頁面,如果條件

class ApplicationController < ActionController::Base 
    @offline = 'true' 
    redirect_to :root if @offline = 'true' 
    protect_from_forgery 
end 

編輯 這就是我現在沒有成功嘗試。默認的控制器不是應用程序控制器。

這給出了一個瀏覽器錯誤Too many redirects occurred trying to open 「http://localhost:3000/countdown」. This might occur if you open a page that is redirected to open another page which then is redirected to open the original page.

如果我添加&& return,動作不會被調用。

回答

3

除了傑德的答案

需要比較運營商,而不是賦值運算符:

redirect_to :root if @offline == 'true' 

如果您遇到更多困難,請將simp lify測試:

redirect_to(:root) if @offline == 'true' 

或者它應該是一個真正的布爾值而不是字符串?

redirect_to :root if @offline 

class ApplicationController < ActionController::Base 
    before_filter :require_online 

private 
    def require_online 
     redirect_to(:root) && return if @offline == 'true' 
    end 
end 
+0

我喜歡這種方法。我將如何重定向到'ApplicationController'中的一個函數?我對Rails完全陌生。 :) –

+0

我可能是錯的,但你不能在ApplicationController中調用動作,對吧?我仍然收到錯誤。 –

+0

@kevin你可以在應用程序控制器中調用redirect_to。你得到的錯誤是什麼? –

0

需要比較運營商,而不是賦值運算符:

redirect_to :root if @offline == 'true' 

如果您遇到更多的困難,簡化測試用:

redirect_to(:root) if @offline == 'true' 

或者,也許它應該是一個真正的布爾值,而不是一個字符串?

redirect_to :root if @offline 
0

Redirect_to應該從動作中調用。

舉個例子,

class ApplicationController < ActionController::Base 
    protect_from_forgery 

    def index 
    @offline = 'true' 

    // Once you do the redirect make sure you return to avoid a double render error. 
    redirect_to :root && return if @offline == 'true' // Jed was right use a comparison 
    end 
end 

看看在 '重定向' docs

+0

作爲旁。您還在控制器類定義中使用了一個實例變量,該變量不能從動作訪問。如果你想要類似的行爲(持續行動),你可能想使用類變量'@@離線',但我的猜測是你沒有;) – diedthreetimes