我正在寻找一些关于redirect_to的行为的澄清。
我有这样的代码:
if some_condition
redirect_to(path_one)
end
redirect_to(path_two)如果为some_condition == true,我会得到这个错误:
在此操作中多次调用了
呈现和/或重定向。请注意,您只能调用render或redirect,并且每个操作最多调用一次。
在redirect_to调用之后,该方法似乎会继续执行。我需要像这样写代码吗:
if some_condition
redirect_to(path_one)
return
end
redirect_to(path_two)发布于 2011-04-21 19:43:01
可以,进行重定向时需要从方法返回。它实际上只为响应对象添加了适当的标头。
你可以用更多的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发布于 2011-04-21 19:42:45
来自http://api.rubyonrails.org/classes/ActionController/Base.html
如果在某些情况下需要重定向,那么一定要加上“
return”来停止执行。
def do_something
redirect_to(:action => "elsewhere") and return if monkeys.nil?
render :action => "overthere" # won't be called if monkeys is nil
end发布于 2012-11-27 08:42:13
你也可以这样做
redirect_to path_one and return读起来不错。
https://stackoverflow.com/questions/5743534
复制相似问题