jkeuhlen
jkeuhlen

Reputation: 4517

How to update deeply nested models that accept nested attributes?

I have a problem mostly identical to this one.

I have three models call them Parent, Child, Grandchild.

Parent
has_many :children
has_many :grandchildren, through: children

When creating a parent, I assign children to it via collection check boxes. Now I need to update grandchildren association on the parent form. I set up

accepts_nested_attributes_for :children

and I am able to update the attributes just like I need to.

The problem arises when I attempt to update a parent record. If I remove a child (through unclicking it's checkbox) I end up with the error

ActiveRecord::RecordNotFound
Couldn't find Child with ID=# for Parent with ID=#

even though this association is well defined in the database. On further investigation I found out the error was coming from

activerecord (4.1.1) lib/active_record/nested_attributes.rb:545:in `raise_nested_attributes_record_not_found!'

Does anyone know how to solve this problem?

Ruby 1.9.3, Rails 4.1.1

In my controller I have

      params.require(:Parent).permit(:name, child_attributes: [:id, :grandchild_id],  :child_ids => [])

Upvotes: 1

Views: 898

Answers (1)

cbartondock
cbartondock

Reputation: 683

Apparently this arises from a security hole related to using existing ids in HABTM relationships. See:

https://groups.google.com/forum/#!topic/rubyonrails-core/uWQVCKqQMVU

https://groups.google.com/forum/?fromgroups#!topic/rubyonrails-security/-fkT0yja_gw

The functionality will not be reintroduced

Upvotes: 1

Related Questions