您在操作中调用before_action :correct_user
get之前重定向请求.@comment.delete
destroy
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
您可以改进的其他一些事项:
@comment = current_user.comments.find_by(id: params[:id])
find_by
这里多余.如果您使用id
以获取记录,请使用find
.
@comment = current_user.comments.find(params[:id])
find
也有引发ActiveRecord::RecordNotFound
错误的好处,这转化为生产中未找到的404响应.
如果要重定向,则不需要执行此操作:
redirect_to request.referrer || root_url
你可以这样做redirect_to :back
,这是在Rails中.
最后,我会重命名你correct_user
的set_comment
.我不认为correct_user
表达了代码的意图,即加载评论.你最终应该这样:
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