我正在使用rails5嵌套表单和 我的嵌套表格如下所示
允许的参数
params.require(:audit_type).permit(:name, :total_score, :id,
risk_scoring_attributes: [:low, :medium, :high, :zero_tolerance, :_destroy, :id],
audit_ratings_attributes: [ :id, :from, :to, :description, :_destroy])
查看
<%= nested_form_for(@audit_type, method: :patch) do |f| %>
<div class="table-responsive">
<table class="table table-search table-striped table-responsive" id="condensedTable">
<thead>
<tr>
<th>From</th>
<th>To</th>
<th>Result</th>
<th>Actions</th>
</tr>
</thead>
<tbody id='audit_rating_data'>
<%= f.fields_for :audit_ratings, @audit_type.audit_ratings, :wrapper => false do |builder| %>
<tr class="<%= cycle("odd", "even") -%> number-cell fields">
<td class="v-align-middle semi-bold">
<%= builder.number_field :from, placeholder: "#", class: 'from_field', required: true %>
</td>
<td class="v-align-middle">
<%= builder.number_field :to, placeholder: "#", class: 'to_field', required: true %>
</td>
<td class="v-align-middle semi-bold">
<%= builder.text_area :description, class: "text-uppercase", required: true %>
</td>
<td class="v-align-middle">
<%= builder.link_to_remove "<i class='fa fa-trash-o'></i>".html_safe, class: "btn btn-rounded btn-danger" %>
</td>
</tr>
<% end %>
</tbody>
</table>
<%= f.link_to_add "<i class='fa fa-plus'></i>".html_safe, :audit_ratings, class: "btn btn-rounded btn-primary", :data => { :target => "#audit_rating_data" } %>
</div>
<% end %>
并且在模型中有关系
has_many :audit_ratings
accepts_nested_attributes_for :audit_ratings, allow_destroy: true
更新时如果我删除任何关联的记录,它将参数传递为
"audit_ratings_attributes"=>{"0"=>{"from"=>"10", "to"=>"20", "description"=>"test", "_destroy"=>"false"}, "1"=>{"from"=>"10", "to"=>"20", "description"=>"test", "_destroy"=>"1"} }
我观察到它在更新时缺少id属性,实际上它是作为嵌套表单的隐藏字段。所以它创造新记录而不是删除。
提前致谢
答案 0 :(得分:0)
解决方案是为id
fields_for audit_ratings
添加隐藏字段,例如:
<%= builder.hidden_field :id, :value => builder.object.id %>