Adding a delete link for nested attributes

后端 未结 3 744
情话喂你
情话喂你 2021-01-18 04:46

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          


        
相关标签:
3条回答
  • 2021-01-18 05:02

    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.

    0 讨论(0)
  • 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 to add :allow_destroy => true in your accepts_nested_attributes definition and add

    <%= l.check_box '_destroy' %>
    

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

    0 讨论(0)
  • 2021-01-18 05:28

    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
    
    0 讨论(0)
提交回复
热议问题