I came across Ryan Bates’ complex-form-examples project when I needed to build a complex form recently. It’s an excellent educational reference for building these complex forms in a Rails app. You know the kind of forms, the ones where you want to add or remove an arbitrary number of child associations of a parent record. True to form, the latest version of Ryan’s example app uses Rails’ new accepts_nested_attributes_for
, which lets you create, edit or delete the collection of associated child objects just by passing through the appropriate attributes to the parent record.
The example app works beautifully, but a couple of its approaches didn’t match how I wanted to build my app:
application.js
or another file dedicated to my JavaScript and behaviour.So when I incorporated Ryan’s examples into my application, I made a couple of changes:
application.js
along with the rest of my JavaScript.display: none
rule. The JavaScript function finds these fields in the DOM and then duplicates them and inserts them into the right place. In essence, the hidden fields act as a template.data-association
to store the appropriate association name for the child. The JavaScript uses this field to find the right hidden template fields (see above). Neat!I applied these changes to an unobtrusive-jquery branch in my fork of complex-form-examples. Please clone or fork it to take a look and make any improvements! I hope it can come in handy. Thanks to Ryan Bates for his excellent work in building the example application.