Adding a delete link for nested attributes
I have nested attributes in my show.erb and I create a blan开发者_StackOverflow社区k 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 %>
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:
- Add
:allow_destroy => true
in youraccepts_nested_attributes
definition - Add
:_allow_destroy
to your controller's strong params - 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.
For those finding this from Google, while technically a delete checkbox might be the correct way, I think it is confusing - the only benefit is that it requires two clicks to delete (select box and hit update). It might be better to just ensure the delete is clear what is happening, and possibly add an easy way to get it back.
The following is to send the update to the server as ajax, to handle updating the page in a callback or js view file. Remove remote: true and it will work as a regular link.
# For my form I build a new object if it's missing,
# so I need to check that this is not a new nested attribute.
- unless question.answers.new_record?
# Basically, I am sending over the fields that would be sent
# by the _delete check box form being updated.
= link_to "Delete", question_path(question.id, question: { answers_attributes: { id: question.answers.id, "_destroy" => true }}), remote: true, confirm: "Really delete?", method: :put
The variable you're using l
isn't correct. When you yield from a fields_for
block the block object is an instance of FormBuilder
not an instance of the object itself. What url do you want the link to point to? Is it Answers#destroy
? What id do you want to send to this action for it to identify what to destroy? A link_to
isn't a form element. It's just a helper for an anchor tag. You need a url, not a form builder to build that link.
Is this going to be a list of answer forms? One for each answer? If so, you might want to loop through them instead of just using fields_for
.
Hopefully this helps you get on the right track.
精彩评论