我非常接近这一点,但却抓住了一个小细节。我正在尝试更新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循环将更新限制为仅适用于shipment_id。我的问题是这是由update action
调用的以下sqlProductShipment 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 %>
答案 0 :(得分:1)
@shipment.product_shipments.each do |product_shipment|
product_shipment.update_attributes(:qty_shipped => params[:product_shipments][product_shipment.id][:qty_shipped])
end
您不必完成所有这些操作,只需使用嵌套表格即可。这是Rails!
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 %>