Rails7删除Post跳转索引页报ActiveRecord::RecordNotFound错误
Rails 7 删除帖子后报RecordNotFound无法返回索引页修复
问题基本信息
- 开发环境:Ruby 3.0.3、Rails 7.0.3
- 错误表现:在帖子详情页触发删除操作后,抛出
ActiveRecord::RecordNotFound in PostsController#show异常,提示无法找到对应ID的Post记录,不能自动跳转回帖子列表页
核心问题点
- 控制器
destroy动作语法错误:原有代码中respond_to do posts_path为无效写法,既没有正确配置HTTP响应,也没有执行跳转逻辑,帖子删除成功后没有给前端返回正确的跳转指令。 - Rails 7默认集成Turbo,非GET请求(这里是DELETE请求)执行成功后的重定向必须返回303状态码,否则Turbo会使用原DELETE方法请求跳转地址,触发异常。
- 原有
index动作没有加载帖子列表数据,即使跳转成功也会因缺少实例变量报错。
修复步骤
1. 修正PostsController代码
将控制器代码替换为以下正确版本:
class PostsController < ApplicationController before_action :find_post, only: [:show, :edit, :update, :destroy] def index # 加载所有帖子数据,供索引页渲染 @posts = Post.all.order(created_at: :desc) end def new @post = Post.new end def create @post = Post.new post_params if @post.save redirect_to @post, notice: "Post has been saved" else render 'new', alert: "Post could NOT be saved" end end def show; end def edit; end def update if @post.update post_params redirect_to @post, notice: "Your article has been updated" else render 'edit' end end def destroy @post.destroy # 删除成功后303重定向到列表页,适配Turbo规则 redirect_to posts_path, status: :see_other, notice: "Post was successfully deleted." end private def post_params params.require(:post).permit(:title, :content) end def find_post @post = Post.find(params[:id]) end end
说明:
status: :see_other对应HTTP 303状态码,是Turbo处理POST/PUT/DELETE等非GET请求后重定向的标准要求,能告诉Turbo用GET方法请求跳转后的列表页地址,避免请求方法错误。
2. 视图部分调整
现有详情页的删除链接写法正确,不需要修改:
<%= @post.title %><br> <%= @post.content %> <br><br> <%= link_to "Edit", edit_post_path(@post) %> <%= link_to "Delete", post_path(@post), data: { turbo_method: :delete, turbo_confirm: 'Are you sure?' } %>
需要补全索引页app/views/posts/index.html.erb的列表渲染逻辑,参考代码:
<h1>Post List</h1> <% @posts.each do |post| %> <div class="post-item"> <h3><%= link_to post.title, post_path(post) %></h3> <p><%= post.content.truncate(120) %></p> </div> <% end %> <p><%= link_to "Create New Post", new_post_path %></p>
3. 其他文件检查
现有路由配置、数据库迁移文件写法完全符合规范,不需要调整。
修改完成后重启Rails服务,再次测试删除功能即可正常删除帖子并自动跳转回帖子索引页,不会再出现记录找不到的报错。
内容的提问来源于stack exchange,提问作者Eduardo Bertrand
相关产品推荐
相关产品推荐

