0

我非常接近这个,但赶上了一个小细节。我正在尝试更新 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'%>&nbsp<%=@product.product_name %>
4

1 回答 1

1
@shipment.product_shipments.each do |product_shipment|
   product_shipment.update_attributes(:qty_shipped => params[:product_shipments][product_shipment.id][:qty_shipped])
end

您不必做所有这些,只需使用嵌套表单。这是铁轨!

http://railscasts.com/episodes/196-nested-model-form-part-1

你的参数应该是这样的

{:product_shipments => { 79 => { :qty_shipped => 450 }, 80 => { :qty_shipped => 35 } }, :shipment_id => 1 }

为此,您应该像这样命名您的字段

<input name="product_shipments[79][qty_shipped]" value="450" />
<input name="product_shipments[80][qty_shipped]" value="35" />

要生成它,

<% @shipment.product_shipments.each do |product_shipment| %>
  <%= text_field_tag "product_shipments[#{product_shipment.id}][qty_shipped]", product_shipment.qty_shipped || 0 %>
<% end %>
于 2012-07-05T05:10:51.123 回答