【问题标题】:redirect_to != return重定向到!=返回
【发布时间】:2011-04-21 11:38:09
【问题描述】:

我正在寻找有关redirect_to 行为的一些说明。

我有这个代码:

if some_condition
   redirect_to(path_one)
end

redirect_to(path_two)

如果some_condition == true 我得到这个错误:

在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。

似乎该方法在redirect_to 调用之后继续执行。我需要这样写代码吗:

if some_condition
   redirect_to(path_one)
   return
end

redirect_to(path_two)

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    是的,重定向时需要从方法返回。它实际上只是为响应对象添加了适当的标头。

    你可以写更多的rubyish方式:

    if some_condition
        return redirect_to(path_one)
    end
    
    redirect_to(path_two)
    

    或其他方式:

    return redirect_to(some_condition ? path_one : path_two)
    

    或其他方式:

    redirect_path = path_one
    
    if some_condition
        redirect_path = path_two
    end
    
    redirect_to redirect_path
    

    【讨论】:

      【解决方案2】:

      来自http://api.rubyonrails.org/classes/ActionController/Base.html

      如果您需要在 某事的条件,然后确定 添加“并返回”以停止执行。

      def do_something
        redirect_to(:action => "elsewhere") and return if monkeys.nil?
        render :action => "overthere" # won't be called if monkeys is nil
      end
      

      【讨论】:

      • 如果为了更好地构建代码,您将重定向放在控制器中的私有“帮助器”方法中。我假设该私有方法中的返回表单无法完成这项工作,对吗?处理这个问题的惯用方法是什么?还是必须将所有重定向放在控制器操作的顶层?
      • @pitosalas 见guides.rubyonrails.org/action_controller_overview.html#filters。它说If a "before" filter renders or redirects, the action will not run.
      • 现在有些人认为使用运算符and 是个坏主意,因为它违反直觉。在这种情况下,and 按预期工作,但 Rubocop 仍然会抱怨。
      【解决方案3】:

      你也可以这样做

      redirect_to path_one and return
      

      读起来不错。

      【讨论】:

      • 如果 redirect_to 返回 false 或 nil 会发生什么?这不是说 return 语句不会被执行吗?或者这就是本意? redirect_to 文档没有指定它的返回值是什么。
      【解决方案4】:

      值得注意的是,没有需要return,除非您在redirect_to之后有任何代码,如本例所示:

      def show
        if can?(:show, :poll)
          redirect_to registrar_poll_url and return
        elsif can?(:show, Invoice)
          redirect_to registrar_invoices_url and return
        end
      end
      

      【讨论】:

        【解决方案5】:

        Eimantas' answer中的“rubyish方式”示例合并为两行代码:

        return redirect_to(path_one) if some_condition
        
        redirect_to(path_two)
        

        【讨论】:

          【解决方案6】:

          如果您想在方法或辅助函数中定义重定向并在控制器中提前返回:

          ActionController::Metal#performed? - 测试渲染或重定向是否已经发生:

          def some_condition_checker
            redirect_to(path_one) if some_condition
          end
          

          这样称呼:

          some_condition_checker; return if performed?
          
          redirect_to(path_two)
          

          【讨论】:

            猜你喜欢
            • 2015-12-11
            • 2015-09-04
            • 2017-08-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-07-18
            • 2015-11-09
            • 2017-05-16
            相关资源
            最近更新 更多