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

时间:2011-07-01 19:17:53

标签: ruby-on-rails conditional-statements reroute

如果条件为真,我想重定向用户:

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

修改 这就是我现在正在尝试但没有成功。默认控制器不是应用程序控制器。

class ApplicationController < ActionController::Base
    before_filter :require_online 

    def countdown

    end

private
  def require_online
    redirect_to :countdown
  end

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 个答案:

答案 0 :(得分:4)

除了杰德的回答

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

 redirect_to :root if @offline == 'true'

如果您遇到进一步的困难,请使用以下方法简化测试:

 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

答案 1 :(得分:0)

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

redirect_to :root if @offline == 'true'

如果您遇到进一步的困难,请使用以下方法简化测试:

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

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

redirect_to :root if @offline

答案 2 :(得分: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