Rails: Delete nested form object dinamically -
i have form add nested objects, this:
this principal form:
#purchasing_goals.html.erb <%= f.fields_for :group_goals |builder| %> <%= render partial: 'group_goal_fields', locals: { f: builder } %> <% end %> <div> <%= link_to_add_fields("add", f, :group_goals) %> </div>
and 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 helpers add , 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}") |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, adds new item when click "add" button, when click "delete" button deletes item in form not in params of form, when click submit button empty nested object sent controller, how can make delete button delete item not in form (visually) delete created object?
thanks in advance
you should use following:
<% content_tag :div, class: "group-goal", id: f.options[:child_index] %> <%= f.text_field :num_of_users, label: "no. usuarios" %> <%= f.text_field :discount_percentage, label: "descuento" %> <%= f.hidden_field(:_destroy) %> <%= link_to "remove", "#", class: "remove", %> <% end %>
this allow use following:
#app/assets/javascripts/application.js $(".group_goal a.remove").on("click", function(e){ $(this).parents(".group_goal").remove(); });
you must remember "dynamic" fields_for
elements html field elements, , can removed dom javascript/jquery.
you're using old railscast way of achieving (those link_to_add_fields
helper methods outdated).
the typical way achieve use cocoon
gem, or manually using answers this: rails accepts_nested_attributes_for f.fields_for , ajax
Comments
Post a Comment