2017-04-21 109 views
2

的Rails:3.2.18Rails的嵌套fields_for用的has_many關係

我試圖建立它接受屬性的關係的has_many嵌套形式。在這種情況下,表單的格式爲Listing,它接受Shipment的屬性,該屬性也接受屬性並具有許多ShipmentPackages。下面就來看看代碼:

# listing.rb 
class Listing < ActiveRecord::Base 
    has_one :shipment 
    accepts_nested_attributes_for :shipment 
end 

# shipment.rb 
class Shipment < ActiveRecord::Base 
    has_many :shipment_packages 
    accepts_nested_attributes_for :shipment_packages 
end 

# Here's the form itself: 
= form_for(@listing) do |f| 
    = f.fields_for :shipment do |shipment_form| 
    - @listing.shipment.shipment_packages.each do |shipment_package| 
     = shipment_form.fields_for 'shipment_packages_attributes[]', shipment_package do |shipment_package_form| 
     = shipment_package_form.text_field(:length) 

# listings_controller.rb 
class ListingsController < ApplicationController 
    def update 
    @listing.update_attributes(params[:listing]) 
    end 
end 

當提交表單時,參數越來越在我預料的方式傳遞他們是:

Parameters: {"listing"=>{"shipment_attributes"=>{"shipment_packages_attributes"=>{"3"=>{"length"=>"11"}, "4"=>{"length"=>"6"}}} 

在這種情況下,id S的我現有的兩個ShipmentPackages分別是34;因此這是我期望看到的。但是,這不會更新現有的ShipmentPackages(3和4)的屬性,而是忽略它們並正在創建全新的ShipmentPackage記錄。我的Shipment現在擁有4 ShipmentPackages(3,4,5,6)。

讓我知道是否有任何進一步的細節會有所幫助。

回答

2

嘗試改變形式包括idshipment_packages_attributes哈希:

{"listing"=>{"shipment_attributes"=>{"shipment_packages_attributes"=>{"3"=>{"id" => "3", "length"=>"11"}, "4"=>{"id" => "4", "length"=>"6"}}} 
+1

你救了我的命,我感激不盡!最後爲每個對象添加一個包含ID的'hidden_​​field'。這個伎倆。不知道爲什麼這是必要的,但謝謝! –

+0

這是迄今爲止或將永遠存在的最偉大的答案! :-O – jeffdill2