Adding a delete link for nested attributes

I have nested attributes in my show.erb, and I create an empty nested attribute and show a grid of elements with an empty row at the bottom like this.

<%= 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 link_to 'Destroy' to work, but I get an undefined method 'plural' when I add this to the grid

 <%= link_to 'Destroy', l, :controller => "answer", :confirm => 'Are you sure?', :method => :delete %> 
+6
source share
3 answers

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

All you have to do is add :allow_destroy => true to the definition of accepts_nested_attributes and add

 <%= l.check_box '_destroy' %> 

for each entry. Thus, it deletes all nested records with a checked flag when saving a record.

+21
source

For those who find it with Google, although technically the deletion flag may be correct, I think this is confusing - the only advantage is that it takes two clicks to delete (select the field and click "Update"). Perhaps it would be better to just make sure that the deletion is clear what is happening, and perhaps add an easy way to get it back.

Next, send the update to the server as ajax in order to process the page update in the callback or in the js view file. Remove the remote: true and it will work as a normal link.

 # For my form I build a new object if it 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 
+9
source

The variable you are using is not valid l . When you return from the fields_for block, the block object is an instance of FormBuilder , not an instance of the object itself. What URL do you want to link to? Is it Answers#destroy ? What identifier do you want to send to this action to determine what needs to be destroyed? A link_to not a form element. This is just an assistant for the anchor tag. To create this link, you need a URL, not a form builder.

Will this be a list of response forms? One for each answer? If so, you can skip them, and not just use fields_for .

I hope this helps you get on the right track.

+1
source

Source: https://habr.com/ru/post/895609/


All Articles