Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 469
Artilheiro Avatar asked Aug 23 '09 00:08

Artilheiro


People also ask

How do I delete an object in rails?

By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.

How do you delete an object in Ruby?

You can't explicitly destroy object. Ruby has automatic memory management. Objects no longer referenced from anywhere are automatically collected by the garbage collector built in the interpreter.


2 Answers

<%= 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 
like image 189
Ian Bishop Avatar answered Sep 19 '22 19:09

Ian Bishop


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 %> 
like image 27
Kostas Rousis Avatar answered Sep 17 '22 19:09

Kostas Rousis