2012-07-05 152 views
0

我在這一個非常接近,但抓住了一個小細節。我正在嘗試更新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'%>&nbsp<%=[email protected]_name %> 

回答

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

您的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 %> 
+0

越來越如下:NoMethodError(對於nil:NilClass,未定義方法'[]'): – ctilley79

+0

您應該在表單中設置字段及其名稱來解決此問題。 '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

+0

使用瑞恩的寶石不是一種選擇。我編輯了這個問題,以包含params散列的內容以及我發現的一些分析。似乎傳遞shipment_id是不合要求的,因爲這是shipment.update_attributes已包含的內容。我沒有嘗試過,但仍然得到同樣的錯誤,因爲我的第一個評論。 – ctilley79