Joshua
Joshua

Reputation: 83

Delete comment link not working (acts_as_commentable)

In my Rails app, each post has a comment section where users can leave comments. I want each comment to have a delete link but I just can't get it to work. I am using the acts_as_commentable gem here.

posts/show.html.erb

<% @comments.each do |comment| %>
  <p><strong><%= comment.user.username %></strong></p>
  <p class="comment"><%= comment.comment %><p>
  <%= link_to "Delete", [@post, comment], method: :delete %> 
<% end %>

I need help with this line

<%= link_to("Delete", [@post, comment], method: :delete %> 

comments_controller.rb

def create 
  @post = Post.find(params[:post_id]) 
  @comment = @post.comments.create(comment_params) 
  @comment.user_id = current_user.id 
end

def destroy
  @comment = Comment.find(params[:id])
  redirect_to :back
end 

Thanks for your help! :)

Upvotes: 0

Views: 70

Answers (2)

Nitin
Nitin

Reputation: 7366

change destroy action something like this:

def destroy
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.destroy
  redirect_to :back
end

In this way you can make sure you are deleting comment related to specific post. It's rails proffered way you can look at it here .

Upvotes: 0

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You are not destroying it at all in the destroy action, you need to add @comment.destroy to delete the comment from database

def destroy
  @comment = Comment.find(params[:id]
  @comment.destroy # add this line
  redirect_to :back
end 

Hope that helps!

Upvotes: 1

Related Questions