我非常接近这个,但赶上了一个小细节。我正在尝试更新 has_many :through 关系。当我提交编辑表单时,我无法提取我想要更新的适当属性。更新发货数量的循环不会使用正确的值更新该字段。如何从 params[:product_shipments] 哈希中仅提取 qty_shipped 属性?
This is the contents of my params[:product_shipments] hash that the update action is working with
"product_shipments"=> {"82"=>{"qty_shipped"=>"234"},
"83"=>{"qty_shipped"=>"324"},
"84"=>{"qty_shipped"=>"324"}},
"commit"=>"Update Shipment", "id"=>"250"}
其中包含我更新货件所需的所有信息,因为 @shipment.product_shipments 循环将更新限制为仅适用的 shipping_id。我的问题是这是更新操作调用的以下 sql
ProductShipment Load (0.3ms) SELECT `product_shipments`.* FROM `product_shipments` WHERE `product_shipments`.`shipment_id` = 250
BEGIN
UPDATE `product_shipments` SET `qty_shipped` = 1 WHERE `product_shipments`.`id` = 82
COMMIT
BEGIN
UPDATE `product_shipments` SET `qty_shipped` = 1 WHERE `product_shipments`.`id` = 83
COMMIT
BEGIN
UPDATE `product_shipments` SET `qty_shipped` = 1 WHERE `product_shipments`.`id` = 84
COMMIT
这是生成上述 sql 的更新操作:
def update
@shipment = Shipment.find(params[:id])
@shipment.update_attributes(params[:shipment])
@shipment.product_shipments.each do |shipment|
shipment.update_attributes(:qty_shipped=> params[:product_shipments])
end
respond_with @shipment, :location => shipments_url
end
不首选使用 rbates nested_forms gem,因为我想弄清楚这一点是为了了解 Rails 的工作原理。
<%= hidden_field_tag("product_shipments[][#{product_shipment.id}]") %>
<%= hidden_field_tag("product_shipments[][product_id]", product_shipment.id) %>
<%= text_field_tag "product_shipments[][qty_shipped]", product_shipment.qty_shipped,:class => 'shipment_qty_field'%> <%=@product.product_name %>