ruby-on-railsrubyhyperlink

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


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?


Solution

  • This answer is from 2009. It appears in Rails 7 (can't confirm, haven't worked in rails in 15 years) the correct answer using turbo can be found below.


    <%= 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