<fieldset class="nested">
<legend>Ingredienti</legend>
<ol id='ingredients'>
<%= render :partial => 'dummy_hidden_fields' %>
<%= fields_for :quantities do |recipe_quantities| %>
<li class="fields">
<%= recipe_quantities.select :ingredient_id, options_from_collection_for_select(ingredients_for_select, :id, :name_unit, recipe_quantities.object.ingredient_id) %>
...
<%# fields_for will automatically generate a hidden field to store the ID of the record, so the following line is not necessary %>
<%#= recipe_quantities.hidden_field_tag 'recipe[quantities_attributes][][id]', dq.id %>
<%# when you use a form element with the _destroy parameter, with a value that evaluates to true, you will destroy the associated model (eg. 1, ‘1’, true, or ‘true’) %>
<%= recipe_quantities.hidden_field :_destroy, 0value: 0 %>
<%= link_to_function "elimina", "remove_ingredient(this)", :class => 'btn btn-mini' %>
</li>
<% end %>
</ol>
<%= link_to_function "Add ingredient", "add_ingredient()" %>
Instead of using a hidden li to add new ingredients, to use a template, like in this example (written in haml):
%h1 Edit Task Collection
= form_tag task_collection_update_path, :method => :put do
%table#tasks
%tr
%th Name
%th Priority
- @tasks.each do |task|
= fields_for 'tasks[]', task, :hidden_field_id => true do |task_form|
= render :partial => 'task_form', :locals => {:task_form => task_form}
= button_tag 'Save'
= button_tag "Add task", :type => :button, :id => :add_task
%script{:type => 'html/template', :id => 'task_form_template'}
= fields_for 'tasks[]', Task.new, :index => 'NEW_RECORD', :hidden_field_id => true do |task_form| render(:partial => 'task_form', :locals => {:task_form => task_form}); end
:javascript
$(function(){
task_form = function(){ return $('#task_form_template').text().replace(/NEW_RECORD/g, new Date().getTime())}
var add_task = function(){ $('#tasks').append(task_form()) }
$('#add_task').on('click', add_task)
})