Note that there are some explanatory texts on larger screens.

plurals
  1. POUnobtrusive dynamic form fields in Rails with jQuery
    text
    copied!<p>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.</p> <p>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 <code>has_many</code> relationship, and I am completely at a loss.</p> <p>Every example I've seen so far has been ugly in one way or another. Ryan Bates' <a href="http://pragprog.com/titles/fr_arr/advanced-rails-recipes" rel="noreferrer">tutorial</a> 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 <a href="http://github.com/timriley/complex-form-examples" rel="noreferrer">fork</a> 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.</p> <p>Can somebody provide a simple example of how this is done? Is this even possible while respecting the RESTful convention of the controllers?</p> <hr> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload