You need to enable JavaScript to run this app. Rails 6 如何在表单下方表格仅展示用户最新提交的Inputs数据
优惠活动
大模型
产品
解决方案
定价
更多

Rails 6 如何在表单下方表格仅展示用户最新提交的Inputs数据

实现思路及代码示例

1. 调整页面结构,新增专属展示表格

在index.html.erb原有表单代码的下方,新增仅用来展示当前用户提交记录的表格,移除原有全量数据展示的表格即可:

<!-- 原有表单代码结束后新增以下内容 -->
<h3>您提交的记录</h3>
<table class="index-table">
  <thead>
    <tr>
      <td>Proveedor</td>
      <td>Factura</td>
      <td>Fecha</td>
      <td>Producto</td>
      <td>Precio Unit.</td>
      <td>Cantidad</td>
      <td>Costo</td>
      <td>Ubicación</td>
    </tr>
  </thead>
  <tbody id="new-inputs-tbody">
    <!-- 后续新提交的记录将动态插入到此处 -->
  </tbody>
</table>

2. 修改控制器Create动作,适配AJAX请求

你当前用的form_with已经配置了local: false开启远程提交,只需要调整Inputs控制器的create方法,响应JS格式请求即可:

# app/controllers/inputs_controller.rb
def create
  @input = Input.new(input_params)
  respond_to do |format|
    if @input.save
      format.js # 保存成功,渲染对应JS模板处理前端逻辑
    else
      format.js { render :error } # 验证失败,渲染错误处理模板
    end
  end
end

private
def input_params
  # 确保参数白名单包含所有表单提交的字段
  params.require(:input).permit(:supplier_id, :invoice, :input_date, :product_id, :price, :quantity, :location, :user_id)
end

3. 添加JS模板处理提交响应

在app/views/inputs目录下新建两个JS模板,分别处理提交成功和失败的场景:

提交成功模板 create.js.erb

// 拼接新记录的表格行代码
const newRow = `
  <tr>
    <td><%= @input.supplier&.name %></td>
    <td><%= @input.invoice %></td>
    <td><%= @input.input_date&.strftime("%Y-%m-%d") %></td>
    <td><%= @input.product&.name %></td>
    <td><%= @input.price %></td>
    <td><%= @input.quantity %></td>
    <td><%= @input.price.to_f * @input.quantity.to_f %></td>
    <td><%= @input.location %></td>
  </tr>
`
// 将新行插入到表格最顶部,需要插到底部就把prepend改成append
$("#new-inputs-tbody").prepend(newRow)
// 清空表单内容,方便用户下一次提交
$("#new-input")[0].reset()

提交失败模板 error.js.erb

// 清空原有错误提示,插入最新错误信息
$("#error_explanation").remove()
const errorHtml = `
  <div id="error_explanation">
    <h2><%= pluralize(@input.errors.count, "error") %> prohibited this input from being saved:</h2>
    <ul>
      <% @input.errors.each do |error| %>
        <li><%= error.full_message %></li>
      <% end %>
    </ul>
  </div>
`
$("#new-input").prepend(errorHtml)

可选优化:页面加载时展示当前用户近期记录

如果希望页面刷新后仍然能看到当前用户之前提交的记录,可以直接在新增表格的tbody中预渲染当前用户的最新记录:

<tbody id="new-inputs-tbody">
  <%# 可自行调整limit数值控制展示条数,也可以去掉limit展示当前用户所有历史记录 %>
  <% current_user.inputs.order(created_at: :desc).limit(20).each do |input| %>
    <tr>
      <td><%= input.supplier&.name %></td>
      <td><%= input.invoice %></td>
      <td><%= input.input_date&.strftime("%Y-%m-%d") %></td>
      <td><%= input.product&.name %></td>
      <td><%= input.price %></td>
      <td><%= input.quantity %></td>
      <td><%= input.price.to_f * input.quantity.to_f %></td>
      <td><%= input.location %></td>
    </tr>
  <% end %>
</tbody>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 19:45:06