ruby-on-rails - 重定向到!=返回

标签 ruby-on-rails

我正在寻找有关 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/

相关文章:

ruby-on-rails - Rails activeadmin 自定义 View 和关联

javascript - React Router 服务器端渲染 Rails

jquery - 为什么向 HTML 页面元素添加 CSS 类会破坏 Turbolinks 获取的页面上的滚动?

ruby-on-rails - 在 RoR 中引用同一个表的多个外键

Ruby-on-Rails:设计自定义失败应用程序问题

ruby-on-rails - 直接链接(无重定向)到 ActiveStorage 中的文件

ruby-on-rails - 如何生成 CSV 文件?

javascript - YUI 编辑器 : How to use CSS to format content of editor window?

ruby-on-rails - 如何在 Rails 中处理带有陈旧 CSRF 真实性 token 的页面

ruby-on-rails - 如何禁用 assets on rails 3.2 的生成器