Ruby on rails 将_重定向到!=返回
我正在寻找一些关于Ruby on rails 将_重定向到!=返回,ruby-on-rails,Ruby On Rails,我正在寻找一些关于重定向到行为的澄清 我有以下代码: if some_condition redirect_to(path_one) end redirect_to(path_two) 如果some_condition==true我得到这个错误: 在此操作中多次调用渲染和/或重定向。请注意,您只能调用render或redirect,每个操作最多只能调用一次 在重定向\u到调用之后,该方法似乎继续执行。我是否需要编写如下代码: if some_condition redirect_
重定向到行为的澄清
我有以下代码:
if some_condition
redirect_to(path_one)
end
redirect_to(path_two)
如果some_condition==true
我得到这个错误:
在此操作中多次调用渲染和/或重定向。请注意,您只能调用render或redirect,每个操作最多只能调用一次
在重定向\u到
调用之后,该方法似乎继续执行。我是否需要编写如下代码:
if some_condition
redirect_to(path_one)
return
end
redirect_to(path_two)
发件人:
如果您需要在
事情的状况,那么一定要确定
添加“并返回”以停止执行
是的,在执行重定向时需要从方法返回。它实际上只为响应对象添加适当的头
你可以用更红的方式写:
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
或者另一种方式:
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 path_one and return
这看起来不错。值得注意的是,除非在重定向到
之后有任何代码,否则没有必要返回
,如本例所示:
def show
if can?(:show, :poll)
redirect_to registrar_poll_url and return
elsif can?(:show, Invoice)
redirect_to registrar_invoices_url and return
end
end
要将“rubysh way”示例合并为两行代码:
return redirect_to(path_one) if some_condition
redirect_to(path_two)
如果要在方法或帮助函数中定义重定向并在控制器中提前返回:
-测试是否已发生渲染或重定向:
def some_condition_checker
redirect_to(path_one) if some_condition
end
这样称呼它:
some_condition_checker; return if performed?
redirect_to(path_two)
如果为了更好地构造代码,您将重定向放在控制器中的私有“helper”方法中会怎么样。我假设这个私有方法中的返回表单不会起作用,对吗?处理这个问题的惯用方法是什么?或者你必须把所有重定向放在控制器操作的顶层吗?@pitosalas-See。它说如果“before”过滤器呈现或重定向,该操作将不会运行。
现在有些人认为使用操作符和是个坏主意,因为它的优先级违反直觉。在这种情况下,和
按预期工作,但Rubocop仍会抱怨。如果重定向到曾经返回false或nil,这里会发生什么?这不意味着return语句不会被执行吗?或者这就是目的?重定向到文档没有指定其返回值。