Rails评论删除功能异常:发送GET请求而非DELETE请求
解决Rails评论删除时发送GET请求而非DELETE请求的问题
问题现象
- 删除评论时,系统发送的是GET请求而非预期的DELETE请求
- 启用
before_action :correct_User, only: [:destroy]前置动作时,即便当前登录用户是评论创建者,仍会弹出Unauthorized to delete the comment错误 - 注释该前置动作后,点击删除按钮依然发送GET请求,页面刷新后返回404 Not Found,请求URL为
http://localhost:3000/posts/27/comments
原因分析
- 路由参数传递错误:嵌套路由
post_comment_path需要同时传入post和comment两个参数,原视图代码只传了comment,导致Rails生成了错误的请求路径 - Rails UJS未正确加载:
button_to的method: :delete依赖UJS实现请求方法转换,若UJS未加载,会 fallback 到GET请求 - 前置动作方法命名不规范:方法名不符合Rails约定(应为小写开头),不过这不是核心问题
解决方案
1. 修正视图中的路由参数
修改_comment.html.erb中的删除按钮代码,传入post和comment两个对象:
<% if current_user.id == comment.user_id %> <%= button_to 'Delete', post_comment_path(comment.post, comment), method: :delete %> <% end %>
之前仅传递comment时,Rails无法正确解析嵌套路由,生成了/posts/27/comments(评论集合路径)而非正确的/posts/27/comments/:id(单个评论的删除路径),这是导致404和GET请求的核心原因。
2. 确保Rails UJS正常加载
- 若使用Rails 6及以下版本,检查
app/assets/javascripts/application.js中是否包含://= require rails-ujs - 若使用Rails 7+(Importmap方式),检查
app/javascript/application.js中是否有:import "@rails/ujs"
UJS负责将button_to生成的表单请求方法从POST转换为DELETE,缺失的话会默认使用GET请求。
3. 规范前置动作方法(可选,若重新启用)
将correct_User方法名改为符合Rails约定的correct_user,保持代码风格一致:
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
4. 验证路由配置
运行rails routes命令,确认嵌套路由的删除路径正确:
post_comment DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
确保生成的请求URL与该路由匹配。
内容的提问来源于stack exchange,提问作者Tomax47
相关产品推荐
相关产品推荐

