我为演示目的简化了更新表单:
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");
})
})
以下内容发送到服务器:
Processing by DesignerLayoutsController#update as HTML
Parameters: { ... "designer_layout"=>{"designer_panels_attributes"=>{"0"=>{"_destroy"=>"1", "id"=>"5"}}} ...
如您所见,具有值“1”的_destroy属性将与特定面板的id一起发送。但是,不删除属于布局的面板。为什么呢?
答案 0 :(得分:1)
在模型中设置allow_destroy: true
:
accepts_nested_attributes_for :designer_panels, allow_destroy: true
并确保使用强参数<{1}}将_destroy
列入白名单:
params.require(:designer_layout).permit(designer_panels_attributes: [:id, :_destroy])