Car*_*ate 5 ruby model-view-controller controller ruby-on-rails ruby-on-rails-4
我有一个简单的模型和控制器。我们以猕猴桃为例:
def index
@kiwis = Kiwi.all
end
def destroy
kiwi = Kiwi.find(params[:id])
kiwi.destroy
redirect_to 'index'
end
Run Code Online (Sandbox Code Playgroud)
我在索引页面上使用了删除链接。当我使用 redirect_to 'index' 页面不会刷新模型。我必须在页面上进行硬刷新才能删除 Kiwi。但是,如果我使用 redirect_to action: 'index' 或 redirect_to kiwis_path 页面将在销毁操作后更新。我似乎无法找到对此的解释。任何人都可以对这个问题有所了解。
在大多数情况下,建议使用命名的路由助手。在您的情况下,正确的做法是redirect_to kiwis_path.
当您调用 redirect_to 时,Rails 将以 302(重定向)状态响应当前请求,然后客户端(即您的浏览器)将向指定位置发出另一个请求。重定向的位置由传递给 的参数决定redirect_to。
当你传递 aString给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
在这里您可以阅读有关redirect_to接受的不同参数及其处理方式的信息。
redirect_to 'index'?我已经设置了一个测试控制器/操作以使用redirect_to 'index'. 让我们看看使用 curl 向它发出请求时会发生什么。
~/projects/gitlab $ curl -v -H "Accept: text/html" http://localhost:3000/redirect_test
Run Code Online (Sandbox Code Playgroud)
我省略了输出的一些不相关部分:
> 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!
Run Code Online (Sandbox Code Playgroud)
您可以在最后一行看到 Location 标头的值不是所需的 URL。当我在 Chrome 中测试时,请求在遇到此错误重定向时被取消。因此浏览器停留在同一页面上并且没有导航离开。这将解释为什么您必须执行“硬刷新”才能查看页面上的更改。
| 归档时间: |
|
| 查看次数: |
3182 次 |
| 最近记录: |