I have a form for add nested objects, like this:
This is the principal form:
#purchasing_goals.html.erb
<%= f.fields_for :group_goals do |builder| %>
<%= render partial: 'group_goal_fields', locals: { f: builder } %>
<% end %>
<div>
<%= link_to_add_fields("Add", f, :group_goals) %>
</div>
and this is the nested form:
<div class="group-goal">
<%= f.text_field :num_of_users, label: "No. Usuarios" %>
<%= f.text_field :discount_percentage, label: "Descuento" %>
<%= f.hidden_field(:_destroy) %>
<%= link_to_remove_fields("Delete", f, "'.group-goal'") %>
</div>
and these are the helpers for add and remove group_goals items:
def link_to_remove_fields(name, f, removal_class)
link_to name, "javascript:void(0);", onclick: "remove_fields(this, #{removal_class})"
end
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(name, "javascript:void(0);", onclick: "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
It works great, it adds a new item when you click the "Add" button, however when I click the "Delete" button it deletes the item in the form but not in the params of the form, so when I click the submit button an empty nested object is sent to the controller, How can I make the delete button delete the item not only in the form (visually) but also delete the created object?