如何在嵌套关联下从Orders索引视图更新订单记录
解决订单索引视图无法触发Update动作的问题
1. 修正控制器初始化逻辑
- 添加
before_action确保在需要的动作中获取当前Building实例 - 调整
index方法,仅获取当前建筑关联的订单,而非所有订单
修改后的orders_controller.rb:
class OrdersController < ApplicationController before_action :get_building, only: [:index, :create] def index @orders = @building.orders end def create @order = @building.orders.build(order_params) if @order.save flash[:info] = "Encomenda cadastrada!" redirect_to building_orders_path(@building) else render 'new' end end def edit @order = Order.find(params[:id]) end def update @order = Order.find(params[:id]) if @order.update(order_params) redirect_to building_orders_path(@order.building), notice: "Encomenda entregue!" else render 'edit' end end private def get_building @building = Building.find(params[:building_id]) end def order_params params.require(:order).permit(:order_id, :name, :apartment, :recipient, :delivered, :mailbox, :building_id) end end
2. 修正订单索引视图的表单逻辑
- 修复HTML结构:每个订单对应独立的
<tr>标签,避免嵌套错误 - 表单绑定循环中的单个订单对象,让Rails自动生成指向
update动作的PATCH请求 - 优化表单显示,填充已有值提升用户体验
修改后的views/orders/index.html.erb:
<table class="table table-striped"> <thead> <tr> <th>Destinatário</th> <th>Apartamento</th> <th>Guichê</th> <th>ID</th> <th>Entregue à</th> <th>Ação</th> </tr> </thead> <tbody> <% @orders.each do |order| %> <tr> <td><%= order.recipient %></td> <td><%= order.apartment %></td> <td><%= order.mailbox %></td> <td><%= order.id %></td> <%= form_with model: order, local: true do |form| %> <td><%= form.text_field :delivered, placeholder: "Entregue à", value: order.delivered %></td> <td><%= form.submit "Marcar como entregue", class: "btn btn-sm btn-primary" %></td> <% end %> </tr> <% end %> </tbody> </table>
3. 问题根源解析
- 无法触发update动作:原视图使用未定义的
@order,form_with默认生成指向create的POST请求;绑定循环中的order实例后,Rails会识别为已有记录,自动生成PATCH请求指向update动作。 - 参数缺失错误:原表单未正确关联订单对象,导致参数未被包裹在
:order键下;修正表单model参数后,参数会被正确传递到控制器。 - HTML结构异常:原代码将所有订单内容嵌套在单个
<tr>内,引发渲染混乱,修正后每个订单对应独立表格行,避免布局错误。
内容的提问来源于stack exchange,提问作者Cleber Reizen
相关产品推荐
相关产品推荐

