简答
建议在大多数情况下使用命名路由助手。在你的情况下,正确的做法是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 中测试时,请求在遇到此错误重定向时被取消。因此,浏览器停留在同一页面上,并没有离开。这可以解释为什么您必须执行“硬刷新”才能看到页面上的更改。