ryanb / nested_form

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

Deeply nested forms cause JS selector problems, wrong input names #77

Closed groe closed 12 years ago

groe commented 13 years ago

When using deeply nested forms, i.e. a nested form inside of a nested form, the jQuery selector 'input:first' could match an input-element that belongs to an already initialized subform instead of the nested form itself. This leads to wrong input-names, that do not match the nesting structure.

Example

Using 5 models:

Now we nest the UserHobby Form into the UserForm and the UserHobbyLocation Form again in the UserHobby Form. So the form has a hierarchy like this:

Screenshot

Now in the form when clicking the _link_toadd of UserHobby and then the _link_toadd of UserHobbyLocation, the nested_forms jQuery selects the wrong input-field to get the context of the new form. Actually it goes down to the hidden '_destroy'-input of the UserHobbyLocation (!) if one exists already and uses this for naming the elements of the new subform.

Possible bugfix

I fixed this for me by using closestChild('input:first') instead of find('input:first') - this way it searches hierarchically for that input element. But since closestChild is not available in jQuery itself (I couldnt find anything similar here) I am using a jQuery plugin for that. Actually "closestChild" is the same as jQuerys 'closest'-function, but it goes down the DOM instead of traversing it up.

I am going to fork this and show you my fix, maybe this helps.

groe commented 13 years ago

I have submitted a pull request fixing this issue, see #78.

groe commented 13 years ago

I have created a sample rails 3.1rc6 project to easily reproduce the issue.

See https://github.com/groe/nested_form-issue-77

Hope that helps.

groe commented 12 years ago

I just updated to nested_form 0.2.2 and this still seems to be a problem. I updated my sample app to reproduce the issue at https://github.com/groe/nested_form-issue-77 (see the README there for instructions on how to reproduce the problem exactly).

Pulling again, that one should apply cleanly against master. @lest