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

Rails 7 Turbo Stream/Frame问题:创建新项后无法返回索引页追加内容

解决Turbo Stream创建后返回索引页并追加新项的问题

问题根源

你的代码已经实现了用Turbo Stream追加新deal到列表,但Turbo Stream默认只会执行DOM局部更新,不会自动触发页面跳转,所以创建成功后会停留在表单页面。

解决方案

1. 修改Turbo Stream响应,添加重定向指令

在create.turbo_stream.haml中,追加内容后添加重定向动作,让Turbo在更新DOM后跳转到索引页:

= turbo_stream.prepend "deals", partial: "deals/deal", locals: { deal: @deal }
= turbo_stream.redirect_to deals_path

2. 确保表单支持Turbo提交

确认new.html.haml中的表单启用Turbo(Rails默认已开启,若未生效可手动指定):

%h1 New deal
= simple_form_for(@deal, data: { turbo: true }) do |f|
  %div
    = f.input :name
  %div
    = f.submit

3. 完善控制器的异常处理

为了避免保存失败时无响应,补充控制器create动作的失败分支:

def create
  @deal = Deal.new(deal_params)
  respond_to do |format|
    if @deal.save
      format.turbo_stream
      format.html { redirect_to deals_path, notice: 'Deal was successfully created.' }
    else
      format.html { render :new, status: :unprocessable_entity }
      format.turbo_stream { render turbo_stream: turbo_stream.replace(@deal, partial: 'deals/form', locals: { deal: @deal }) }
    end
  end
end

原理说明

turbo_stream.redirect_to会向Turbo发送指令,在完成DOM局部更新(追加新deal)后,导航到索引页面。这样既实现了新项的动态追加,又回到了列表页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:32:51