Daniel Viglione
Daniel Viglione

Reputation: 9407

_destroy attribute not destroying record

I have simplified my update form for demo purposes:

class DesignerLayout < ActiveRecord::Base
  has_many :designer_panels, dependent: :destroy
  accepts_nested_attributes_for :designer_panels

_form.html.erb

<%= form_for @designer_layout do |f| %>
  <%= f.fields_for :designer_panels, @designer_layout.designer_panels do |designer_panel_builder| %>
    <%= designer_panel_builder.hidden_field :_destroy %>
    <%= link_to '#', class: 'remove-item' do %>
      <%= content_tag :span %>
    <% end %>
  <% end %>
<% end %>

form.js

$(document).ready(function(){
  $('.remove-item').click(function(){
    $(this).prev('input[type="hidden"]').val("1");
  })
})

The following is sent to server:

Processing by DesignerLayoutsController#update as HTML
   Parameters: { ... "designer_layout"=>{"designer_panels_attributes"=>{"0"=>{"_destroy"=>"1", "id"=>"5"}}} ...

As you can see, the _destroy attribute with a value of "1" is sent with the id of the specific panel. However, the panel belonging to the layout is not deleted. Why?

Upvotes: 0

Views: 121

Answers (1)

dp7
dp7

Reputation: 6749

Set allow_destroy: true in model:

accepts_nested_attributes_for :designer_panels, allow_destroy: true

And, make sure to whitelist the _destroy using strong param:

params.require(:designer_layout).permit(designer_panels_attributes: [:id, :_destroy])

Upvotes: 1

Related Questions