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

3
我想在条件为真时重定向用户:
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

这会导致浏览器出现错误:尝试打开“http://localhost:3000/countdown”时发生了太多重定向。如果您打开的页面被重定向到打开另一个页面,然后再次被重定向回原始页面,则可能会发生此情况。

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

3个回答

5
除了Jed的回答之外,需要使用比较运算符而非赋值运算符:

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

 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

我喜欢这种方法。我如何将重定向 ApplicationController 中的函数?我完全是 Rails 的新手。 :) - Kevin Brown
我可能错了,但你不能直接在 ApplicationController 中调用 actions,对吧?我仍然在收到错误信息。 - Kevin Brown
@kevin,你可以在应用控制器中调用redirect_to。你遇到了什么错误? - Mohit Jain
抱歉回复晚了。请看我的编辑。似乎根本没有调用重定向。我也尝试添加 && return - Kevin Brown
我使用了 :except => :countdown - Kevin Brown
显示剩余4条评论

1

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

请查看'Redirect' docs


顺便提一下,您还在控制器类定义中使用实例变量,这些变量无法从操作中访问。如果您想要类似的行为(跨操作持久化),您可能希望使用类变量@@offline,但我猜您不需要;) - diedthreetimes

0
需要比较运算符,而不是赋值运算符:
redirect_to :root if @offline == 'true'

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

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

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

redirect_to :root if @offline

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接