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

Rails 7:调用show action时触发Turbo Stream更新查询未读状态

解决方案

1. 修正请求格式,触发Turbo Stream响应

点击表格行打开Turbo Frame时,需要让请求明确指定turbo_stream格式,避免服务器默认返回HTML导致格式不匹配报错。修改表格行的链接:

<%= link_to inquiry_path(inquiry, format: :turbo_stream), data: { turbo_frame: "inquiry_show_frame" } do %>
  <%# 表格行内容 %>
  <% if !inquiry.seen? %>
    <span class="unread-indicator text-blue-500">●</span>
  <% end %>
  <%= inquiry.subject %>
  <%# 其他列内容 %>
<% end %>

2. 简化Show Action逻辑

update!方法会在更新失败时直接抛出异常,无需额外判断,直接更新状态并响应对应格式:

def show
  @inquiry.update!(seen: true)
  respond_to do |format|
    format.html
    format.turbo_stream do
      flash.now[:notice] = "Anfrage angesehen."
    end
  end
end

3. 创建Turbo Stream模板更新表格行

在app/views/inquiries/目录下新建show.turbo_stream.erb,编写流操作替换表格中对应的行(假设表格每行的DOM ID为inquiry_<%= inquiry.id %>,且行内容抽离到_inquiry_row.html.erb局部模板):

<%# 替换目标行,更新未读状态 %>
<%= turbo_stream.replace "inquiry_#{@inquiry.id}", partial: "inquiries/inquiry_row", locals: { inquiry: @inquiry } %>

<%# 可选:更新Flash提示 %>
<%= turbo_stream.update "flash_container", partial: "shared/flash" %>

4. 确认MIME类型配置(若未配置需添加)

确保config/initializers/mime_types.rb中已注册Turbo Stream类型:

Mime::Type.register "text/vnd.turbo-stream.html", :turbo_stream

问题根源

之前的406 Not Acceptable错误是因为请求未指定turbo_stream格式,服务器无法匹配对应响应格式;同时缺少Turbo Stream模板更新表格,导致状态更新后页面无变化。通过明确请求格式+编写流更新模板,即可实现标记已读后表格实时移除未读蓝点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:15:43