I'm new to rails and I'm trying to implement my own dynamic fields using jquery. I've got the fields adding to the form fine, but my parameters are not being sent the way I want them to. Here is my jQuery:
$('form').on('click', '#add_ingredient', function(){
count = 1;
field = $('#ingredient_list li').first()
.clone()
.find('input')
.val('')
.end()
.find('input')
.prop({id: 'entry_ingredients_attributes_' + count + '_name', name: 'entry[ingredients_attributes][' + count +'][name]' })
.end();
$('#ingredient_list').append(field);
count += 1;
})
This allows me to add multiple list items and their id's and name get incremented so they are unique.
I've got the models setup correctly to use accepts_nested_attributes_for, I'm creating a baking journal which has models Entry, Ingredient, and the association EntryIngredient. My problem is as follows:
When I submit the form, I am only sending one of the ingredients even if I've added multiple fields, only the last one gets submitted. This is the output of my paramters when I submit a form with anything more than 1 ingredient:
"ingredients_attributes"=>{"0"=>{"name"=>"Flour", "_destroy"=>"false"}, "1"=>{"name"=>""}}}}
Here is my form as well in case you are interested to see how its being created:
<div id="ingredients">
<%= f.fields_for :ingredients, @entry.ingredients.build do |builder| %>
<%= render 'ingredient_fields', :f => builder %>
<% end %>
</div>
<div id='add_ingredient'>Add Ingredient</div>
<div class="actions">
<%= f.submit %>
#_ingredient_fields
<ul id="ingredient_list">
<li>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.hidden_field :_destroy %>
<%= link_to "Remove", "#", :class => "remove_fields" %>
</li>
</ul>
Can anyone point me in the right direction?
SOLUTION
Following Zaid Crouch's suggestion in the answer below, it turned out that my selectors were not doing the right thing. My JS is now like so:
$('form').on('click', '#add_ingredient', function(){
count = $('#ingredient_list li').length;
field = $('#ingredient_list li').first()
.clone()
.find('input')
.val('')
.end()
.find('input :first')
.prop({id: 'entry_ingredients_attributes_' + count + '_name', name: 'entry[ingredients_attributes][' + count +'][name]' })
.end()
.find('input :last')
.prop({id: 'entry_ingredients_attributes_' + count + '__destroy', name: 'entry[ingredients_attributes][' + count +'][_destroy]', value: 'false' })
.end();
$('#ingredient_list').append(field);
})
If anyone can recommend a better way to select those elements I'm changing the properties on I'd appreciate the feedback.