Rails: 3.2.18
I am attempting to build a nested form which accepts attributes for a has_many relationship. In this case the form is for a Listing which is accepting attributes for a Shipment which is also accepting attributes for and has many ShipmentPackages. Here's a look at the code:
# 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
When the form is submitted, the parameters are getting passed in the way I would expect them to be:
Parameters: {"listing"=>{"shipment_attributes"=>{"shipment_packages_attributes"=>{"3"=>{"length"=>"11"}, "4"=>{"length"=>"6"}}}
In this case, the ids of my two existing ShipmentPackages are 3 and 4; therefore this ^ is what I would expect to see. However, rather than updating the attributes of the existing ShipmentPackages (3 and 4), this ignores them and is creating brand new ShipmentPackage records. My Shipment now owns 4 ShipmentPackages (3, 4, 5, 6).
Aucun commentaire:
Enregistrer un commentaire