Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a delete link for nested attributes

I have nested attributes in my show.erb and I create a blank nested attribute and show a grid of items with the blank at the bottom like so.

<%= form_for @question do |q| %>
  <% q.fields_for :answers, @question.answers do |l| %>
    <tr>

      <td><%= l.text_field :text %></td>
      <td><%= l.check_box :correct %></td>
      <td><%= l.text_field :imagename %></td>
      <td><%= l.number_field :x %></td>
      <td><%= l.number_field :y %></td>
    </tr>
  <% end %>

  <tr>
        <td colspan=5 align=right><%= submit_tag '+' %>
  </tr>

<% end %>

I want a link_to 'Destroy' to work but i'm getting undefined method 'plural' when i add this to the grid

<%= link_to 'Destroy', l, :controller => "answer", :confirm => 'Are you sure?', :method => :delete %>
like image 558
Joseph Le Brech Avatar asked Aug 22 '11 16:08

Joseph Le Brech


1 Answers

Why do you want to use a link? You can also use the destroy functionality in the nested attributes.

All you need to do is:

  1. Add :allow_destroy => true in your accepts_nested_attributes definition
  2. Add :_allow_destroy to your controller's strong params
  3. Add <%= l.check_box '_destroy' %> to your template

That way it removes all the nested records with the check-box checked when saving the record.

like image 180
Jimmy Stenke Avatar answered Oct 23 '22 10:10

Jimmy Stenke