redirect_to!=返回

dem*_*mas 61 ruby-on-rails

我正在寻找关于行为的一些澄清redirect_to.

我有这个代码:

if some_condition
   redirect_to(path_one)
end

redirect_to(path_two)
Run Code Online (Sandbox Code Playgroud)

如果some_condition == true我收到此错误:

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

似乎该方法在redirect_to调用后继续执行.我需要编写这样的代码:

if some_condition
   redirect_to(path_one)
   return
end

redirect_to(path_two)
Run Code Online (Sandbox Code Playgroud)

Eim*_*tas 92

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

你可以写更多rubyish方式:

if some_condition
    return redirect_to(path_one)
end

redirect_to(path_two)
Run Code Online (Sandbox Code Playgroud)

或其他方式:

return redirect_to(some_condition ? path_one : path_two)
Run Code Online (Sandbox Code Playgroud)

或另一种方式:

redirect_path = path_one

if some_condition
    redirect_path = path_two
end

redirect_to redirect_path
Run Code Online (Sandbox Code Playgroud)


Vas*_*ich 29

来自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
Run Code Online (Sandbox Code Playgroud)

  • @pitosalas请参阅http://guides.rubyonrails.org/action_controller_overview.html#filters.它说`如果"之前"过滤器呈现或重定向,则该动作将不会运行 (4认同)
  • 如果为了更好地构建代码,可以将重定向放在控制器中的私有"帮助器"方法中.我假设私有方法里面的返回表单不能完成这项工作,对吗?处理这个问题的惯用方法是什么?或者您是否必须将所有重定向放在控制器操作的顶层? (3认同)
  • 现在有些人认为使用运算符`和`是一个坏主意,因为它具有违反直觉的优先权.在这种情况下,`和`按预期工作,但仍然,_Rubocop_会抱怨. (2认同)

Rim*_*ian 24

你也可以

redirect_to path_one and return
Run Code Online (Sandbox Code Playgroud)

哪个读得不错.