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

Rails 7中如何在Turbo Frame内删除记录并跳转至外部页面?

解决Rails 7 Turbo Frame内删除记录后跳转异常问题

问题原因

你遇到的错误是因为Turbo默认会在发起请求的Turbo Frame上下文内处理响应,即使设置了turbo_target: "_top",DELETE请求的响应仍会被尝试匹配原Frame,导致找不到对应id="frame"的元素而报错。

解决方案

方案1:强制整页导航(最直接)

给删除链接添加data-turbo="false",绕过Turbo的Frame内处理逻辑,强制浏览器整页提交请求并跳转:

<%= turbo_frame_tag 'frame' do %>
  <%= link_to "Delete", url_for(writable), 
    data: { 
      turbo: false, 
      turbo_method: :delete, 
      turbo_confirm: 'Are you sure?' 
    }, 
    class: "button" %>
<% end %>

修改后,点击删除链接确认后,浏览器会以传统方式处理请求,删除记录后正常跳转到records_path,不会触发Frame匹配错误。

方案2:通过Turbo Stream返回导航指令

如果想保留Turbo的特性,可在控制器的destroy动作中返回Turbo Stream的导航指令,明确告诉Turbo要整页跳转:

def destroy
  @record = Record.find(params[:id])
  @record.destroy

  respond_to do |format|
    format.html { redirect_to records_path, status: :see_other }
    format.turbo_stream do
      render turbo_stream: turbo_stream.redirect(records_path)
    end
  end
end

此时链接可保留原turbo_target: "_top"配置,Turbo会处理返回的Stream指令,完成整页导航。

验证效果

两种方案都能实现:删除记录后成功跳转到独立的列表页面,不再出现Response has no matching <turbo-frame id="frame"> element错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:55:16