【问题标题】:Ruby on Rails - Difference between redirect_to 'index' and redirect_to objects_path & redirect_to action: 'index'Ruby on Rails - redirect_to 'index' 和 redirect_to objects_path 和 redirect_to 动作的区别:'index'
【发布时间】:2017-02-21 10:06:49
【问题描述】:

我有一个简单的模型和控制器。我们以猕猴桃为例:

def index
    @kiwis = Kiwi.all
end

def destroy
    kiwi = Kiwi.find(params[:id])
    kiwi.destroy
    redirect_to 'index'
end

我在索引页面上使用了删除链接。当我使用 redirect_to 'index' 时,页面不会刷新模型。我必须在页面上进行一次硬刷新才能删除 Kiwi。但是,如果我使用 redirect_to action: 'index' 或 redirect_to kiwis_path,页面将在销毁操作后更新。我似乎无法找到对此的解释。谁能解释一下这个问题。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller controller


    【解决方案1】:

    redirect_to 'index' 不是有效代码。 你需要为redirect_to指定一个完整的路径。

    您可能会将其与有效代码 render 'index' 混淆。

    【讨论】:

      【解决方案2】:

      简答

      建议在大多数情况下使用命名路由助手。在你的情况下,正确的做法是redirect_to kiwis_path

      长答案

      当您调用 redirect_to 时,Rails 将以 302(重定向)状态响应当前请求,然后客户端(即您的浏览器)将向指定位置发出 另一个请求。重定向的位置由您传递给redirect_to 的参数决定。

      当您将String 传递给redirect_to 时,它必须是一个URL(带有协议和主机,例如“http://localhost:3000/kiwis”或不带,例如“/kiwis”)

      在您的情况下,redirect_to kiwis_path 是正确的。相当于redirect_to '/kiwis'

      当您传递哈希参数action: 'index' 时,url_for 方法用于生成 URL。

      redirect_to action: 'index'redirect_to url_for(action: 'index') 相同。 url_for(action: 'index') 将匹配您的路径 /kiwis

      因此redirect_to action: 'index' 等同于redirect_to '/kiwis'redirect_to kiwis_path

      Here 您可以阅读redirect_to 接受的不同参数以及如何处理它们。

      redirect_to 'index' 会发生什么?

      我已经设置了一个测试控制器/操作以使用redirect_to 'index' 进行重定向。让我们看看使用 curl 向它发出请求时会发生什么。

      ~/projects/gitlab $ curl -v -H "Accept: text/html" http://localhost:3000/redirect_test
      

      我省略了输出中一些不相关的部分:

      > GET /select_options HTTP/1.1
      > Host: localhost:3000
      > User-Agent: curl/7.43.0
      > Accept: text/html
      >
      < HTTP/1.1 302 Moved Temporarily
      < X-Frame-Options: ALLOWALL
      < X-XSS-Protection: 1; mode=block
      < X-Content-Type-Options: nosniff
      < Location: http://localhost:3000index      <----- That is not what we want!
      

      您可以在显示的最后一行中看到 Location 标头的值不是所需的 URL。当我在 Chrome 中测试时,请求在遇到此错误重定向时被取消。因此,浏览器停留在同一页面上,并没有离开。这可以解释为什么您必须执行“硬刷新”才能看到页面上的更改。

      【讨论】:

      • 非常感谢您的回答和如此详细。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多