Reputation: 24886
I am trying to puzzle out why the accepts_nested_attributes_for
will not destroy a record when it receives a hash like this:
{project_parcels_attributes"=>[{"parcel_id"=>"680060", "_destroy"=>"1"}, {"parcel_id"=>"680088"}]}
The context of use is as follows. There is a Project model:
class Project < ActiveRecord::Base
has_many :project_parcels
accepts_nested_attributes_for :project_parcels, allow_destroy: true
end
class ProjectParcels < ActiveRecord::Base
belongs_to :project
belongs_to :parcel
validates :parcel_id, uniqueness: {scope: :project_id}
end
Then I call it from a form like this:
@project.update_attributes({"project_parcels_attributes"=>[{"parcel_id"=>"680060", "_destroy"=>"1"}, {"parcel_id"=>"680088"}]})
Yet, it doesn't work. The validation stops the record from being destroyed. But when I remove validation, the record gets added multiple times.
Upvotes: 1
Views: 956
Reputation: 1392
you should add the id of the child object by an hidden_field tag
<%= f.hidden_field :id %>
and then update with the id :
{project_parcels_attributes"=>[{id: an_id, "parcel_id"=>"680060", "_destroy"=>"1"}, {id: an_id, "parcel_id"=>"680088"}]}
Upvotes: 2