Rails 嵌套 fields_for 关系 has_many

Rails nested fields_for with has_many relationship

Rails: 3.2.18

我正在尝试构建一个嵌套表单,它接受 has_many 关系的属性。在这种情况下,表单适用于 Listing,它接受 Shipment 的属性,Shipment 也接受 ShipmentPackages 的属性,并且有许多 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"}}}

在这种情况下,我现有的两个ShipmentPackagesid34;因此这 ^ 是我希望看到的。但是,这并没有更新现有 ShipmentPackages(3 和 4)的属性,而是忽略了它们并创建了全新的 ShipmentPackage 记录。我的 Shipment 现在拥有 4 ShipmentPackages (3, 4, 5, 6).

让我知道是否有更多有用的详细信息。

尝试更改表单以将 id 包含在 shipment_packages_attributes 散列中:

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