title: How to add and remove nested model fields dynamically using Haml and Formtastic
body: <p>We've all seen the brilliant <a href="http://railscasts.com/episodes/197-nested-model-form-part-2" rel="noreferrer">complex forms railscast</a> where Ryan Bates explains how to dynamically add or remove nested objects within the parent object form using Javascript.</p>
  
  <p>Has anyone got any ideas about how these methods need to be modified so as to work with Haml Formtastic? </p>
  
  <p>To add some context here's a simplified version of the problem I'm currently facing:</p>
  
  <p># Teacher form (which has nested subject forms) [from my application]</p>
  
  <pre><code>- semantic_form_for(@teacher) do |form|
    - form.inputs do
      = form.input :first_name
      = form.input :surname
      = form.input :city
      = render 'subject_fields', :form =&gt; form 
      = link_to_add_fields "Add Subject", form, :subjects   
  </code></pre>
  
  <p># Individual Subject form partial [from my application]</p>
  
  <pre><code>- form.fields_for :subjects do |ff| 
    #subject_field
      = ff.input :name
      = ff.input :exam
      = ff.input :level
      = ff.hidden_field :_destroy
      = link_to_remove_fields "Remove Subject", ff 
  </code></pre>
  
  <p># Application Helper (straight from Railscasts)</p>
  
  <pre><code>  def link_to_remove_fields(name, f)
      f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
    end
  
    def link_to_add_fields(name, f, association)
      new_object = f.object.class.reflect_on_association(association).klass.new
      fields = f.fields_for(association, new_object, :child_index =&gt; "new_#{association}") do |builder|
        render(association.to_s.singularize + "_fields", :f =&gt; builder)
      end
      link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}  \")"))
    end
  </code></pre>
  
  <p>#Application.js (straight from Railscasts)</p>
  
  <pre><code>  function remove_fields(link) {
    $(link).previous("input[type=hidden]").value = "1";
    $(link).up(".fields").hide();
    }
  
  function add_fields(link, association, content) {
    var new_id = new Date().getTime();
    var regexp = new RegExp("new_" + association, "g")
    $(link).up().insert({
      before: content.replace(regexp, new_id)
    });
    }
  </code></pre>
  
  <p>The problem with implementation seems to be with the javascript methods - the DOM tree of a Formtastic form differs greatly from a regular rails form.</p>
  
  <p>I've seen this question asked online a few times but haven't come across an answer yet - now you know that help will be appreciated by more than just me!</p>
  
  <p>Jack</p>