ryanb / nested_form

Rails plugin to conveniently handle multiple models in a single form.
MIT License
1.79k stars 506 forks source link

Recursive nesting broken in nested_form 0.3.x #237

Open groe opened 11 years ago

groe commented 11 years ago

Today I upgraded an application from nested_form 0.2.3 to 0.3.1 because I noticed there are some changes and new features available (such as passing an collection to fields_for).

After a quick bundle update nested_form I tried to open up the application in my browser but it kept loading (at 100% CPU). As the server log showed, it was rendering the same partial template over and over again.

My model (a typical tree structure): Root has_many Nodes. Node belongs_to Root. Node_belongs to Node (parent). Node has_many Nodes (children).

In nested_form 0.2.3 this would result in one blueprint being reused correctly for all nesting levels. However, since nested_form 0.3.x stores blueprints in a data-attribute when link_to_add gets called, this somehow results in rendering the same fields_for-partial over and over again.

My final solution: Do not call link_to_add in the partial, but instead use some javascript to prepare a blueprint for the next nesting depth. A litte laborious, but it basically works. There remains only one problem with this approach: Since all associations have the same name (i.e. the same data-association attribute) the regular expressions that are used to instantiate a nested form from its blueprint are too generic.

Currently every occurence of <assocName>_attributes and new_<assocName> will be replaced with something. But if there are multiple associations with the same name (as in my particular case with the recursion) the first replace will already catch every occurence and nothing will be left for the other replace-operations. That results in wrong IDs being used and therefore wrong submitted data.

TL;DR nested_form 0.3.x is broken for nesting structures where two or more associations have the same name (as in recursive, tree-like structures) because the regular expressions are too generic

Sailias commented 10 years ago

@groe do you have a helper and/or javascript that implements your "manual" addition of the nested fields?

groe commented 10 years ago

@Sailias It's some time ago I posted this, but if I remember correctly everything I changed should be included in #238.