I'm using the " nathanvda / cocoon" plugin to provide nested forms and I'm using the " crowdint / rails3-jquery-autocomplete" plugin to provide autocomplete functionality. The "Add Image" link on the form view adds a partial view each time it is clicked. So if I've clicked the "Add Image" button twice I get two partials on the form each with an autocomplete field. When I enter text in the automcomplete fields and select one of the entries in the dropdown list, the javascript is triggered. I need the javascript to place the id of the list item in the hidden field id (visual_id). What I'm seeing is that the value is only being set for the first hidden field. The visual_id for any subsequent hidden fields are not set.
Of course when I submit the form, the insert into the database fails because of the missing visual_id for the second nested record.
I hope all that makes sense!
---------------------------------
_form.html.erb
<div>
<%= f.simple_fields_for :groups_visuals do |groups_visual| %>
<%= render 'groups_visual_fields', :f => groups_visual %>
<% end %>
<div class='links'>
<%= link_to_add_association 'Add Image', f, :groups_visuals, :class => "edit-heading-l" %>
</div>
</div>
-----------------------------------
_groups_visual_fields.html.erb
<div class='nested-fields'>
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell1">
<%= link_to_remove_association "Remove", f %>
</div>
<div class="tbl-cell2">
<%= f.input :visual_img_file_name, :label => false, :as => :autocomplete, :url => autocomplete_visual_img_file_name_groups_path, :input_html => {:id_element=>'#visual_id'} %>
<%= f.hidden_field :visual_id, :id => "visual_id" %>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('input').bind('railsAutocomplete.select', function(event, data){
$('#visual_id').val(data.item.id);
});
});
</script>
Here is the nested attributes portion of the save parameters after submitting the form. Notice the visual_id for the second nested record is empty.
"groups_visuals_attributes"=>{"0"=>{"_destroy"=>"", "visual_img_file_name"=>"Kansas1.jpg", "visual_id"=>"44"}, "1"=>{"_destroy"=>"", "visual_img_file_name"=>"LedZepp1973HousesHoly.jpg", "visual_id"=>""}}}, "commit"=>"Save", "id"=>"1493"}