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

后端 未结 3 722
一向
一向 2020-12-24 04:59

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 d

相关标签:
3条回答
  • 2020-12-24 05:33

    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 %>
    
    0 讨论(0)
  • 2020-12-24 05:34
    <%= 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
    
    0 讨论(0)
  • 2020-12-24 05:51

    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/<%=@blog.id%>" data-method="delete">             
      <i class="pg-trash"></i><span class="bold">Delete</span>
    </a>
    
    0 讨论(0)
提交回复
热议问题