How to update deeply nested models that accept nested attributes?

别等时光非礼了梦想. 提交于 2019-12-13 01:29:44

问题


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 => [])

回答1:


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



来源:https://stackoverflow.com/questions/24684986/how-to-update-deeply-nested-models-that-accept-nested-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!