You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hotwire Turbo使用turbo-method: :delete后跳转异常问题咨询

Turbo turbo_method: :delete 跳转异常问题

问题场景

测试ERB代码

<p><%= link_to 'Test', test_path, data: { turbo_method: :delete } %></p>

控制器方法代码

def test
  redirect_to root_path, status: :see_other
end

异常现象

使用版本为@hotwired/turbo-rails": "7.2.4"时,点击链接后Turbo返回turbostream,将根页面内容追加到当前HTML标签中,并未跳转到根页面。

疑问点

  • 是否因为turbo_method生成表单内部执行导致缺失目标?尝试多种设置target的方式,始终是追加内容。
  • turbo_method: :delete 的效果难道不该与Rails UJS的method: :delete一致吗?

问题原因与解决办法

  1. 核心原因:Turbo处理非GET请求(如DELETE)时,默认优先以turbostream格式响应,不会像Rails UJS那样直接遵循重定向跳转页面——这是两者核心行为差异。

  2. 具体解决方式:

    • 方法一:控制器指定响应格式
      在重定向时明确指定format: :html,让Turbo识别为页面跳转请求:
      def test
        redirect_to root_path, status: :see_other, format: :html
      end
      
    • 方法二:链接禁用turbostream
      在链接的data属性中添加turbo_stream: false,强制Turbo按传统方式处理跳转:
      <p><%= link_to 'Test', test_path, data: { turbo_method: :delete, turbo_stream: false } %></p>
      
    • 方法三:全局/控制器层面配置
      若这类场景较多,可在控制器中设置默认响应格式为HTML,或调整Turbo全局配置,但前两种方式更直接高效。

内容的提问来源于stack exchange,提问作者Oliver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:15:16