rails 3.2更新has_many:通过
问题描述:
我在这一个非常接近,但抓住了一个小细节。我正在尝试更新has_many:through关系。当我提交编辑表单时,我无法提取我想更新的适当属性。更新发货数量的循环不会使用正确的值更新该字段。我怎样才能从params [:product_shipments]哈希中只提取qty_shipped属性?rails 3.2更新has_many:通过
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的所有信息。我的问题是,这是通过更新动作
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和这里是产生上面的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宝石不可取的,因为我想为了学习轨道工作的目的,弄清楚这一点。
<%= 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'%> <%=[email protected]_name %>
答
@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
您的PARAMS应该是这样的
{: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 %>
越来越如下:NoMethodError(对于nil:NilClass,未定义方法'[]'): – ctilley79
您应该在表单中设置字段及其名称来解决此问题。 'form_for @shipment do | f | @ shipment.product_shipments.each do | product_shipment | text_field_tag“product_shipments [#{product_shipment.id}] [qty_shipped]”,product_shipment.qty_shipped end end' 当您在rails中使用嵌套窗体时,所有这些都会自动处理。 – SMathew
使用瑞恩的宝石不是一种选择。我编辑了这个问题,以包含params散列的内容以及我发现的一些分析。似乎传递shipment_id是不合要求的,因为这是shipment.update_attributes已包含的内容。我没有尝试过,但仍然得到同样的错误,因为我的第一个评论。 – ctilley79