当前位置:  开发笔记 > 编程语言 > 正文

无法删除Rails中的任何注释模型

如何解决《无法删除Rails中的任何注释模型》经验,为你挑选了1个好方法。



1> Mohamad..:

您在操作中调用before_action :correct_userget之前重定向请求.@comment.deletedestroy

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

推荐阅读
sx-March23
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有