ruby-on-railsnested-formsfields-for

Rails accessing fields_for hidden_field id


I have a nested form with a parent object (full_application) and a collection of child objects (fullapplication_districts) via a has_many association. I am attempting to allow for deletion of individual child objects on the form (via javascript) but to do so I need to be able to grab the id of each child object in the view for passing to the controller. fields_for creates a hidden input field for the id but I can't seem to figure out how to grab the id from it. In the example below the record is the 13th in the list of rendered child objects.

<input type="hidden" value="538" name="full_application[fullapplication_districts_attributes][12][id]" id="full_application_fullapplication_districts_attributes_12_id">

Here's the form setup in the view:

<%= 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 %>

Solution

  • You can use: fad.object or fad.object.id. This will return to fullapplication_district instance.

     <%= 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 %>