How to create a delete link for a related object in Ruby on Rails?

Ruby on-RailsRubyHyperlink

Ruby on-Rails Problem Overview


So let's say I have Posts and Comments and the url for show is /posts/1/comments/1. I want to create a link to delete that comment in the comments controller destroy method. How do I do that?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

<%= link_to 'Destroy', post_comment_path(@post, comment),
            data: {:confirm => 'Are you sure?'}, :method => :delete %>

in comments controller:

  def destroy
    @post = Post.find(params[:post_id])
    @comment = Comment.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html { redirect_to post_comments_path(@post) }
      format.xml  { head :ok }
    end
  end

Solution 2 - Ruby on-Rails

Since some time ago, the confirm option has to be included in a data hash, otherwise it will be silently ignored:

<%= link_to 'Destroy',  post_comment_path(@post, comment),
    data: { confirm: 'Are you sure?' }, method: :delete %>

Solution 3 - Ruby on-Rails

Sometimes when you have <span>, <i> or nested elements inside of a <a> tag this way link_to use is difficult. You can inseted use raw HTML which is easy to handle, like so:

<a class="btn btn-sm" href="/blogs/<%[email protected]%>" data-method="delete">				
  <i class="pg-trash"></i><span class="bold">Delete</span>
</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArtilheiroView Question on Stackoverflow
Solution 1 - Ruby on-RailsIan BishopView Answer on Stackoverflow
Solution 2 - Ruby on-RailsKostas RousisView Answer on Stackoverflow
Solution 3 - Ruby on-RailsaksView Answer on Stackoverflow