ryanb/nested_form — Issue #143: Insertion of (new) fields not adjacent to prior .fields if add link is in another element
Author: motine
Created: 2012-02-15 08:39:03+00:00
State: open

When I added the add_to_link(...) call in another sub-div (for design purposes) the fields appeared in this sub-div and not adjacent to the fields-div.
Example:
<%= f.simple_fields_for :submodels do |fi| %>
...

<%= f.link_to_add "add an invoice", :submodels %>

Resulted in

...

...

<%= f.link_to_add "add an invoice", :submodels %>

My solution in the jquery file:
insertFields: function(content, assoc, link) {
// traverse up the DOM tree to find the closest element (up the tree) with the "fields" class.
var loopLimit = 5; // avoid endless loops
var traverseElm = $(link); // anchor for traversing
do {
traverseElm = traverseElm.parent();
lastFieldsElm = traverseElm.children('.fields:last');
if (loopLimit <= 0)
break;
loopLimit--;
} while (lastFieldsElm.length == 0)
// fall back, if there was no fields at all
if (lastFieldsElm.length == 0) {
return $(content).insertBefore(link);
} else {
return $(content).insertAfter(lastFieldsElm);
}
},