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

So let's say I have posts and comments, and the display URL is /posts/1/comments/1 . I want to create a link to delete this comment in the method of destroying the comment controller. How to do it?

+41
ruby ruby-on-rails hyperlink
Aug 23 '09 at 0:52
source share
3 answers
 <%= link_to 'Destroy', post_comment_path(@post, comment), data: {:confirm => 'Are you sure?'}, :method => :delete %> 

in the comment 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 
+97
Aug 23 '09 at 1:08
source share

Since some time ago, the confirm parameter should be included in the data hash, otherwise it will be silently ignored:

 <%= link_to 'Destroy', post_comment_path(@post, comment), data: { confirm: 'Are you sure?' }, method: :delete %> 
+9
Sep 14 '15 at 13:21
source share

Sometimes, when you have <span> , <i> or nested elements inside the <a> tag in this way, link_ is difficult to use. You can use raw HTML that is easy to process, for example:

 <a class="btn btn-sm" href="/blogs/<%=@blog.id%>" data-method="delete"> <i class="pg-trash"></i><span class="bold">Delete</span> </a> 
0
04 Oct '16 at 9:21
source share



All Articles