title: Rails nested form adds before parent form
body: <p>There is Dog model and Specie model, which belongs to Dog. When create Dog, Rails also generate nested form to add specie, through button 'add specie'. The trouble is that in view after adding nested form takes place before parent form. If I add a lot additional nested forms, parent form is the last form. For sure not good.</p>
  
  <pre><code>class Dog &lt; ActiveRecord::Base
    attr_accessible :name, :species_attributes
    has_many :species
    accepts_nested_attributes_for :species
    validates :name, :presence =&gt; true
  end
  
  class Specie &lt; ActiveRecord::Base
    attr_accessible :name, :specie_id
    belongs_to :dog
    validates :name, :presence =&gt; true
  end
  </code></pre>
  
  <p>&lt;</p>
  
  <pre><code>div class="field"&gt;
      &lt;%= f.label :name %&gt;&lt;br /&gt;
      &lt;%= f.text_field :name %&gt;
    &lt;/div&gt;
      &lt;%= f.fields_for :species do |builder| %&gt;
          &lt;%= render 'specie_fields', :f=&gt; builder %&gt;
      &lt;% end %&gt;
      &lt;%= button_to_add_fields 'Add Specie', f, :species %&gt;
    &lt;div class="actions"&gt;
      &lt;%= f.submit %&gt;
    &lt;/div&gt;
    &lt;% end %&gt;
  </code></pre>
  
  <p>_specie_fields.html.erb:</p>
  
  <pre><code>&lt;div class="field"&gt;
  &lt;%= f.label :name, 'Specie' %&gt; &lt;br /&gt;
  &lt;%= f.text_field :name %&gt;
  &lt;%= f.hidden_field :_destroy %&gt;
  &lt;%= button_to_function 'Specie delete', 'remove_fields(this)' %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>helper method:</p>
  
  <pre><code>module ApplicationHelper
    def button_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
      button_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
    end
  end
  </code></pre>
  
  <p>JS file:</p>
  
  <pre><code> function add_fields(link, association, content) {
          var new_id = new Date().getTime();
          var regexp = new RegExp("new_" + association, "g")
          $(link).parent().before(content.replace(regexp, new_id));
  </code></pre>