Rails:如果条件重定向到页面

Kev*_*own 3 ruby-on-rails reroute conditional-statements

如果条件成立,我想重定向用户:

\n\n
class ApplicationController < ActionController::Base\n  @offline = 'true'\n  redirect_to :root if @offline = 'true'\n  protect_from_forgery\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑\n这就是我现在正在尝试的方法,但没有成功。默认控制器不是应用程序控制器。

\n\n
class ApplicationController < ActionController::Base\n    before_filter :require_online \n\n    def countdown\n\n    end\n\nprivate\n  def require_online\n    redirect_to :countdown\n  end\n\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

这会导致浏览器错误Too many redirects occurred trying to open \xe2\x80\x9chttp://localhost:3000/countdown\xe2\x80\x9d. This might occur if you open a page that is redirected to open another page which then is redirected to open the original page.

\n\n

如果我添加&& return,则该操作永远不会被调用。

\n

Moh*_*ain 5

除了杰德的回答

需要比较运算符,而不是赋值运算符:

 redirect_to :root if @offline == 'true'
Run Code Online (Sandbox Code Playgroud)

如果您遇到更多困难,请使用以下方法简化测试:

 redirect_to(:root) if @offline == 'true'
Run Code Online (Sandbox Code Playgroud)

或者也许它应该是一个真正的布尔值而不是字符串?

 redirect_to :root if @offline
Run Code Online (Sandbox Code Playgroud)
class ApplicationController < ActionController::Base
   before_filter :require_online 

 private
    def require_online
       redirect_to(:root) && return if @offline == 'true'
    end
 end
Run Code Online (Sandbox Code Playgroud)