santosh
santosh

Reputation: 1611

Nested Form Not Passing Id Attribute on Update

I am using rails5 nested form and my nested form is like below

permitted params

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])

View

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

and in model have relation

  has_many :audit_ratings
  accepts_nested_attributes_for :audit_ratings, allow_destroy: true

while updating if i delete any associated records it passing parameters as

"audit_ratings_attributes"=>{"0"=>{"from"=>"10", "to"=>"20", "description"=>"test", "_destroy"=>"false"}, "1"=>{"from"=>"10", "to"=>"20", "description"=>"test", "_destroy"=>"1"} }

what i observed is it missing id attribute on update, actually it comes as a hidden field for Nested form. so its creating new record rather than delete.

Thanks in advance

Upvotes: 1

Views: 997

Answers (1)

Muhammad Ali
Muhammad Ali

Reputation: 2183

Solution will be to add a hidden field for id for audit_ratings fields_for like :

<%= builder.hidden_field :id, :value => builder.object.id %>

Upvotes: 1

Related Questions