我正在寻找有关 redirect_to
行为的一些说明。
我有这个代码:
if some_condition
redirect_to(path_one)
end
redirect_to(path_two)
如果some_condition == true
我收到此错误:
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action.
看来该方法在 redirect_to
调用之后继续执行。我需要编写这样的代码吗:
if some_condition
redirect_to(path_one)
return
end
redirect_to(path_two)
最佳答案
是的,进行重定向时需要从方法返回。它实际上只为响应对象添加适当的 header 。
您可以编写更多 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
关于ruby-on-rails - 重定向到!=返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5743534/