redirect_to != 返回 [英] redirect_to != return
问题描述
我正在寻找有关 redirect_to
行为的说明.
I'm looking for some clarification regarding the behaviour of redirect_to
.
我有这个代码:
if some_condition
redirect_to(path_one)
end
redirect_to(path_two)
如果 some_condition == true
我得到这个错误:
If some_condition == true
I get this error:
在此操作中多次调用渲染和/或重定向.请注意,您只能调用渲染或重定向,并且每个操作最多只能调用一次.
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
调用后,该方法似乎继续执行.我是否需要编写这样的代码:
It seems that the method continues to execute after the redirect_to
call. Do I need to write code like this:
if some_condition
redirect_to(path_one)
return
end
redirect_to(path_two)
推荐答案
是的,重定向时需要从方法中返回.它实际上只是为响应对象添加了适当的标头.
Yes, you need to return from method when doing redirect. It actually only adds appropriate headers for the response object.
你可以写更多的rubyish方式:
You can write more rubyish way:
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
这篇关于redirect_to != 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!