gpt4 book ai didi

ruby-on-rails - Ruby on Rails - redirect_to 'index' 和 redirect_to objects_path & redirect_to action : 'index' 之间的区别

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:39 30 4
gpt4 key购买 nike

我有一个简单的模型和 Controller 。让我们以新西兰人为例:

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 页面将在销毁操作后更新。我似乎找不到对此的解释。任何人都可以阐明这个问题。

最佳答案

简答

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

长答案

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

当您将 String 传递给 redirect_to 时,它必须是一个 URL(带有协议(protocol)和主机,例如“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' 会发生什么?

我已经设置了一个测试 Controller /操作以使用 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 header 的值不是所需的 URL。当我在 Chrome 中测试时,请求在遇到这个错误的重定向时被取消。因此,浏览器停留在同一页面上,并没有离开。这可以解释为什么您必须执行“硬刷新”才能看到页面上的更改。

关于ruby-on-rails - Ruby on Rails - redirect_to 'index' 和 redirect_to objects_path & redirect_to action : 'index' 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40001412/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com