I've been watching Ryan Bates' nested_forms episodes 1 & 2 on RailsCasts, successfully implementing the functionality in one project without any issues. However, in a new project using the same reference, the remove and add field functionality is not working.
Here is my model:
has_many :contacts, :dependent => :destroy
accepts_nested_attributes_for :contacts, :reject_if => lambda { |a| a[:contact_name].blank? }, :allow_destroy => true
The form where I'm trying to use the add field link:
<div class="TabbedPanelsContent">
<%= f.fields_for :contacts do |builder| %>
<%= render "contact_fields", :f => builder %>
<% end %>
<p><%= link_to_add_fields "Add Contact", f, :contacts %></p>
</div>
The partial for contacts:
<div class="fields">
<p class="lable">Contact Name</p>
<p class="field"><%= f.text_field :contact_name %></p></br>
<p class="lable">Mobile Number</p>
<p class="field"><%= f.text_field :contact_mobile_number %></p></br>
<p class="lable">Email Address</p>
<p class="field"><%= f.text_field :contact_email %></p></br>
<p><%= link_to_remove_fields "remove", f %></p> </div>
In the Application helper, I created these methods:
# Method for removing fields
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
# Method for Adding fields
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, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
The application.js looks like this:
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).up(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).up().insert({
before: content.replace(regexp, new_id)
});
}
By using Firebug, I noticed an issue with the generated HTML:
<p><input type="hidden" value="false" name="customer[contacts_attributes][1][_destroy]" id="customer_contacts_attributes_1__destroy"><a onclick="remove_fields(this); return false;" href="#">remove</a></p>
It seems that the value="false" might be causing the problem, as it should be value="1" according to my previous successful implementation. Can someone help me with this issue?