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
分別是3
和4
;因此這是我期望看到的。但是,這不會更新現有的ShipmentPackages
(3和4)的屬性,而是忽略它們並正在創建全新的ShipmentPackage
記錄。我的Shipment
現在擁有4 ShipmentPackages
(3,4,5,6)。
讓我知道是否有任何進一步的細節會有所幫助。
你救了我的命,我感激不盡!最後爲每個對象添加一個包含ID的'hidden_field'。這個伎倆。不知道爲什麼這是必要的,但謝謝! –
這是迄今爲止或將永遠存在的最偉大的答案! :-O – jeffdill2