title: RoR: Nested forms and dynamic fields
body: <p>I am struggling with some nested forms which dynamically inserts fields. I have based my code on Ryan Bates great railscasts.  My problem though is that I need to move my "add fields" button outside the nested form.  This causes problems because I don't have access to some of the objects required to generate the form.</p>
  
  <p>In the code below the add/remove button is in the same location.  I can change the if statement to do this, but I cannot move the add fields button outside the f.simple_fields_for :fund_levels loop.</p>
  
  <p>Any suggestions for a clean way of doing this?</p>
  
  <p>The view</p>
  
  <pre><code>     = f.simple_fields_for :fund_levels do |fl|
         - fl.object.id ? headerappend = fl.object.id : headerappend = "#{i}-notset"
         %div{id: "flheader-#{headerappend}"}
           %div
             = link_to "Sponsor levels", "#", :class =&gt; "show_hide", :id =&gt; "initiator1_fl#{i}", :style=&gt;"margin-bottom:2px;", :onclick=&gt;"return false"
           %div{:class =&gt; "slidingDiv #{fund_levels_last?(i, @fund_level_count) ? "shown": "hidd" } whitebg leftadj", :id=&gt;"body_fl#{i}", :style=&gt;"width:100%;" }
  
             = render :partial =&gt; 'fund_level_fields', :locals =&gt; {:fl =&gt; fl, :ad =&gt; ad, :i =&gt; i, :f =&gt; f}
             %div{:style =&gt; "float: right; padding: 20px 20px 20px 0"}
               = fund_levels_last?(i, @fund_level_count) ? ( link_to_add_fields "add new level", f, :fund_levels, fl, i+1, ad ) : ( link_to "remove", accounts_ad_fund_level_path(ad, fl.object.id), {:class =&gt; 'button orange sm', :method =&gt; :delete, :remote =&gt; true, :confirm =&gt; t('q.are_you_sure')} )
         - i += 1
       %div#newfields
         - # THE BUTTON SHOULD GO HERE if it is an ADD FIELDS (remove btn should stay above)
  </code></pre>
  
  <p>the application_helper file</p>
  
  <pre><code>   def link_to_add_fields(name, f, association, sublevel, counter, parent)
  
       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, :fl =&gt; sublevel, :i =&gt; counter, :ad =&gt; parent) #fl, i, ad
       end
  
       # this bit is required because of some bugs in haml
       fields.gsub!(/\&lt;haml\:newline\/\&gt;/, '').html_safe
  
       link_to name, '#', :id =&gt; "#{name}|-|#{association}|-|#{fields}", :class =&gt; "addfields", :onclick =&gt; "return false"
     end
  </code></pre>