我正在寻找关于行为的一些澄清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)
归档时间: |
|
查看次数: |
23871 次 |
最近记录: |