我有一个嵌套表单,其中包含一个父对象(full_application(和一个子对象集合(fullapplication_districts(,通过has_many关联。我试图允许删除表单上的单个子对象(通过 javascript(,但要做到这一点,我需要能够抓取视图中每个子对象的 id 以传递给控制器。fields_for为 id 创建了一个隐藏的输入字段,但我似乎无法弄清楚如何从中获取 id。在下面的示例中,记录是呈现的子对象列表中的第 13 条记录。
<input type="hidden" value="538" name="full_application[fullapplication_districts_attributes][12][id]" id="full_application_fullapplication_districts_attributes_12_id">
下面是视图中的窗体设置:
<%= form_for(@full_application, url: full_applications_edit_path, method: :put) do |f| %>
<%= f.fields_for :fullapplication_districts do |fad| %>
<%= fad.collection_select :district_id, District.all, :id, :name, {include_blank: true}, {class: 'form-control'} %>
<%= fad.number_field :percent_one, class: 'form-control', step: :any %>
<%= fad.number_field :percent_two, class: 'form-control', step: :any %>
<%= fad.number_field :percent_three, class: 'form-control', step: :any %>
<%= link_to full_applications_districts_path(???), method: :delete, remote: true, data: { confirm: "Are you sure you want to delete this record?" } do %>
<i class="fa fa-trash"></i>
<% end %>
<% end %>
<% end %>
您可以使用
: fad.object
或fad.object.id
。这将返回到fullapplication_district实例。
<%= link_to full_applications_districts_path(fad.object), method: :delete, remote: true, data: { confirm: "Are you sure you want to delete this record?" } do %>
<i class="fa fa-trash"></i>
<% end %>