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:
So when I incorporated Ryan's examples into my application, I made a couple of changes:
- This means the page markup is cleaner. The links to add and remove child elements have no inline JS, just a certain class name for jQuery to hook onto.
- For the form to work with multiple child objects, the links to add new fields include an HTML5 custom data attribute called
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.