Skip to content
This repository was archived by the owner on Dec 12, 2021. It is now read-only.
This repository was archived by the owner on Dec 12, 2021. It is now read-only.

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

@groe

Description

@groe

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:

  • User
  • Hobby
  • Location
  • UserHobby and
  • UserHobbyLocation.
    A User has_many UserHobbys. A Hobby has_many UserHobbys too. A UserHobby itself has_many UserHobbyLocations and a UserHobbyLocation belongs_to a Location. So users can have many hobbys, each one at multiple locations.

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:

  • User attributes
    -- Nested UserHobby attributes (i.e. a Dropdown of all Hobbys)
    --- Nested UserHobbyLocation attributes (i.e. a Dropdown of all Locations)

Screenshot

Now in the form when clicking the link_to_add of UserHobby and then the link_to_add 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions