When I try to delete a comment, it sends a get request instead of a delete one.
When the before_action :correct_User, only: [:destroy]
is active, it shows the error Unauthorized to delete the comment although the user connected is the same who created the comment.
comments controller :
class CommentsController < ApplicationController
#before_action :correct_User, only: [:destroy]
def new
@comment = current_user.comments.new
end
def create
@comment = current_user.comments.new(comment_params)
if @comment.save
redirect_to post_comments_path
else
flash.now[:notice] = "Couldn t create the comment!"
end
end
def destroy
@comment = current_user.comments.find(params[:id])
@comment.comments.destroy_all
if @comment.destroy
redirect_to post_comments_path
else
redirect_to post_comments_path
flash[:notice] = "Couldn t delete the comment!"
end
end
private
def correct_User
@comment = current_user.comments.find_by(id: params[:id])
redirect_to post_comments_path, notice: "You are not authorized to delete this comment!" if @comment.nil?
end
def comment_params
params.require(:comment).permit(:content, :parent_id).merge(post_id: params[:post_id])
end
end
routes.rb :
Rails.application.routes.draw do
#get posts/index
resources :posts do
resources :comments, only: [:create, :destroy]
end
resources :likes, only: [:destroy, :create]
resources :sessions, only: [:create, :destroy]
get sessions/new
get sing_in , to: sessions#new
delete sign_out , to: sessions#destroy
resources :users, only: [:create, :destroy]
get users/new
get /register , to: users#new
root posts#index
end
_comment.html.erb in the comments views :
<article>
<p><strong>@<%= comment.user.username %></strong></p>
<!-- HERE WE ARE REFERENCING THE COMMENT MODEL WITH THE COMMENT DATATYPE IN THE DB-->
<p class="comment-body">
<%= comment.content%>
</p>
<!-- TODO: CHECK OUT WHY THE DELETE FUNCTION AIN T WORKING-->
<% if current_user.id == comment.user_id %>
<%= button_to Delete , post_comment_path(comment), method: :delete %>
<%end %>
<a href="#" class="comment-form-display">Reply</a>
<div class="reply-sub-comment">
<%= render partial: comments/format , locals: {post: comment.post, parent: comment} %>
</div>
<hr />
<div class="sub-comment">
<%= render comment.comments %>
</div>
</article>
</div>
<script>
document.querySelectorAll( .comment-form-display ).forEach((el) => {
el.addEventListener( click , (ev) => {
ev.preventDefault();
el.nextElementSibling.style = display: block;
})
})
</script>
<style>
.sub-comment {
padding-left: 6em;
}
.reply-sub-comment {
display: none;
}
</style>
Request s details : Request URL: http://localhost:3000/posts/27/comments Request Method: GET Status Code: 404 Not Found Remote Address: [::1]:3000 Referrer Policy: strict-origin-when-cross-origin
因此,我试图先发表评论,然后才采取行动,然而,它却无所助,要求删除的纽顿只是寄去要求,并更新网页。