Tuesday, June 5, 2012

Unobtrusive dynamic form fields in Rails with jQuery

I'm attempting to get over the hurdle of dynamic form fields in Rails -- this appears to be something the framework doesn't handle very gracefully. I'm also using jQuery in my project. I have jRails installed, but I'd much rather write the AJAX code unobtrusively where possible.

My forms are fairly complex, two or three levels of nesting are not unusual. The problem I'm having is generating the correct form ids, since they are so dependant on the form builder context. I need to be able to dynamically add new fields or delete existing records in a has_many relationship, and I am completely at a loss.

Every example I've seen so far has been ugly in one way or another. Ryan Bates' tutorial requires RJS, which results in some pretty ugly obtrusive javascript in the markup, and seems to have been written before nested attributes. I've seen a fork of that example with unobtrusive jQuery, but I just don't understand what it's doing, and haven't been able to get it working in my project.

Can somebody provide a simple example of how this is done? Is this even possible while respecting the RESTful convention of the controllers?

Andy has posted an excellent example of deleting an existing record, can anybody provide an example of creating new fields with the correct attributes? I haven't been able to figure out how to do this with nested forms.

Source: Tips4all

No comments:

Post a Comment