views:

23

answers:

0

I'm trying to build a nested form similar to the one here: http://railscasts.com/episodes/197-nested-model-form-part-2

The form is for creating an invoice with items that can be added dynamically:

<div>
  <%= render :partial => 'invoice_item_fields', :locals => { :f => f } %>  
</div>  

<tr id="invoice_items">
  <td colspan=3>
    <%= link_to_add_fields "Neuer Rechnungsposten", f, :invoice_items %>
  </td>  
</tr>

And here is my partial for the nested invoice items:

<% f.fields_for :invoice_items do |invoice_item_form| %>

"> <%= invoice_item_form.text_field :quantity, :size => 3 %> <%= invoice_item_form.text_field :article_number, :size => 7 %> <%= invoice_item_form.text_field :description, :size => 20 %> <%= invoice_item_form.text_field :unit_price, :size => 3 %> <%= invoice_item_form.select :reduced_tax, [ ['Ja', true],['Nein', false] ] %> <%= link_to_remove_fields "Entfernen", invoice_item_form, "Rechnungsposten" %> <% end %>

I copied the link_to_add fields from the screencast to my application_helper: #creates links to dynamically add fields in a form, see h**p://railscasts.com/episodes/197-nested-model-form-part-2 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 => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")) end

...and also the javascript part /** Adds fields dynamically to a form, see h**p://railscasts.com/episodes/197-nested-model-form-part-2 before: content.replace(regexp, new_id) */ function add_fields(link, association, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") $(link).up(1).insert({ before: content.replace(regexp, new_id) }); }

However the index is not properly generated in my application. Here is a form field that is already present from the beginning:

<input type="text" value="85" size="3" name="invoice[invoice_items_attributes][0][quantity]" id="invoice_invoice_items_attributes_0_quantity">

And here is form field that was dynamically added:

<input type="text" size="3" name="invoice[invoice_items_attributes][1281618444550]**[invoice_items]**[quantity]" id="invoice_invoice_items_attributes_1281618444550_invoice_items_quantity">

Of course if I'm trying to save the form I get an error because of the extra [invoice_items] of the dynamically added field. How can I fix this error?

Thanks for your help!