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?
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.
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.
<%= 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
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With