Artilheiro
Artilheiro

Reputation: 4005

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?

Upvotes: 53

Views: 55306

Answers (5)

Ian Bishop
Ian Bishop

Reputation: 5205

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

Upvotes: 111

ahmed khaled
ahmed khaled

Reputation: 31

In rails 7.0.4.2

You can use destroy method this way 'turbo gem'

<%= link_to 'Delete', user, data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>

Turbo gives you the speed of a single-page web application without having to write any JavaScript. Turbo accelerates links and form submissions without requiring you to change your server-side generated HTML. It lets you carve up a page into independent frames, which can be lazy-loaded and operate as independent components. And finally, helps you make partial page updates using just HTML and a set of CRUD-like container tags. These three techniques reduce the amount of custom JavaScript that many web applications need to write by an order of magnitude. You can install 'turbo' in terminal by:

gem install turbo-rails -v 1.0.1

Or in Gemfile and bundled it.

gem 'turbo-rails', '~> 1.0', '>= 1.0.1'

Then

bundle install

Upvotes: 3

installero
installero

Reputation: 9766

Given you have @post variable with your post object

Before Rails 7

<%= link_to 'Delete comment', post_comment_path(@post, comment),
  method: :delete, data: {confirm: 'Are you sure?'} %>

Rails 7 (with Turbo, out of the box)

<%= link_to 'Delete comment', post_comment_path(@post, comment),
  data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>

Upvotes: 10

aks
aks

Reputation: 9491

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/<%[email protected]%>" data-method="delete">             
  <i class="pg-trash"></i><span class="bold">Delete</span>
</a>

Upvotes: 1

Kostas Rousis
Kostas Rousis

Reputation: 6068

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

Upvotes: 11

Related Questions