title: Rails 3 nested model form creates duplicate model objects
body: <p>I've followed along with Ryan Bates' tutorial (<a href="http://railscasts.com/episodes/196-nested-model-form-revised" rel="nofollow">Episode 196 - Nested Model Forms (Revised)</a>) to create a form for a model (<code>Employee</code>) with a nested <code>has_many :through</code> model (<code>Capability</code>). For the most part it works; however, when I click the link to add a new model object to the form, <em>two</em> are created and inserted. I don't know why - I've struggled with this for a few evenings now and just can't work it out. Can anyone point out where I've gone wrong?</p>
  
  <p>(<code>Capability</code> here represents a <code>has_many through</code> association: <code>Employee has_many :roles, through: :capabilities</code>).</p>
  
  <h3>form partial</h3>
  
  <pre><code>&lt;%= form_for(@employee) do |f| %&gt;
  
    # Employee fields here ...
  
    &lt;%= f.fields_for :capabilities do |builder| %&gt;
      &lt;%= render 'capability_fields', f: builder %&gt;
    &lt;% end %&gt;
    &lt;%= link_to_add_fields "Add capability", f, :capabilities %&gt;
  
    &lt;%= f.submit "Submit", :class =&gt; 'submit' %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <h3>capability_fields partial</h3>
  
  <pre><code>&lt;fieldset&gt;
    &lt;%= f.select :role_id, Role.all.collect{ |r| [r.name, r.id]} %&gt;
    &lt;%= f.check_box :primary_role_flag %&gt;
    &lt;%= f.text_field( :valid_from, :class =&gt; 'date') %&gt;
    &lt;%= f.text_field( :expires_on, :class =&gt; 'date') %&gt;
    &lt;%= f.hidden_field :_destroy %&gt;
    &lt;%= link_to "Remove", '#', class: "remove_fields" %&gt;
  &lt;/fieldset&gt;
  </code></pre>
  
  <h3>link_to_add_fields application helper</h3>
  
  <pre><code>def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize + "_fields", f: builder)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub('\n','&amp;#xA')})
  end
  </code></pre>
  
  <h3>jQuery coffeescript</h3>
  
  <pre><code>jQuery -&gt;
    $('form').on 'click', '.remove_fields', (event) -&gt;
      $(this).prev('input[type=hidden]').val('1')
      $(this).closest('fieldset').hide()
      event.preventDefault()
  
    $('form').on 'click', '.add_fields', (event) -&gt;
      time = new Date().getTime()
      regexp = new RegExp($(this).data('id'), 'g')
      $(this).before($(this).data('fields').replace(regexp, time))
      event.preventDefault()
  </code></pre>