Reputation: 43
Deleting other stuff works fine. It looks the same as my post controller (which is working) but doesn't delete the comments.
resources :comments, only: [:create, :destroy]
_comment partial
<% if current_user?(comment.user) %>
<%= link_to "[Delete]", comment, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
comments controller
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def destroy
@comment.destroy
# @comment = @post.comments.find(params[:id]).destroy
flash[:success] = "Comment deleted"
redirect_to @post
end
private
def correct_user
@comment = current_user.comments.find_by(id: params[:id])
redirect_to request.referrer || root_url
end
Upvotes: 1
Views: 87
Reputation: 35349
Your before_action :correct_user
is redirecting the request before the the @comment.delete
gets called in the destroy
action.
def correct_user
@comment = current_user.comments.find_by(id: params[:id])
# This line below is the problem.
redirect_to request.referrer || root_url
end
Some other things that you can improve:
@comment = current_user.comments.find_by(id: params[:id])
find_by
is redundant here. If you are using the id
to fetch the record, use find
.
@comment = current_user.comments.find(params[:id])
find
also has the benefit of raising an ActiveRecord::RecordNotFound
error, which translates to a 404 not found response in production.
If you want to redirect back, you don't need to do this:
redirect_to request.referrer || root_url
You can just do redirect_to :back
, which is in Rails.
Finally, I would rename your correct_user
to set_comment
. I don't think correct_user
expresses the intention of the code, which is to load the comment. You should end up with this:
before_action :set_comment, only: :destroy
def destroy
@comment.destroy
redirect_to :back
end
def set_comment
@comment = current_user.comments.find(params[:id])
end
Upvotes: 5