【问题标题】:Rails: Redirect to page if conditionRails:如果条件重定向到页面
【发布时间】:2011-09-26 23:56:02
【问题描述】:

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

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.

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

【问题讨论】:

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


    【解决方案1】:

    除了杰德的回答

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

     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完全陌生。 :)
    • 我可能是错的,但你不能在 ApplicationController 中调用操作,对吧?我仍然遇到错误。
    • @kevin 您可以在应用程序控制器中调用 redirect_to。你得到的错误是什么?
    • 抱歉回复晚了。请看我的编辑。似乎根本没有调用重定向。我也试过添加&amp;&amp; return
    • @kevin 倒计时动作有一些前置过滤器或某些将其重定向到新页面的东西.. 并从那里重定向到倒计时动作.. 它的多个重定向.. 一种重定向循环..
    【解决方案2】:

    应该从动作中调用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

    【讨论】:

    • 顺便说一句。您还在控制器类定义中使用了一个实例变量,该变量无法从操作中访问。如果您想要类似的行为(跨操作持续存在),您可能需要使用类变量 @@offline,但我猜您不需要;)
    【解决方案3】:

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

    redirect_to :root if @offline == 'true'
    

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

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

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

    redirect_to :root if @offline
    

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 2014-06-10
      • 1970-01-01
      • 2019-05-10
      • 2016-04-11
      • 1970-01-01
      相关资源
      最近更新 更多