You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails命名空间内路由重定向问题:删除项目后跳转报错

解决Rails命名空间控制器中Destroy动作重定向问题

问题根源

  1. 命名空间控制器内,:root默认指向全局路由而非当前命名空间的api_v1_root,导致找不到对应的root_url方法。
  2. 重定向会默认沿用原请求的HTTP方法(此处为DELETE),但api_v1_root仅支持GET请求,因此触发路由不匹配错误。

解决方案

方案1:直接跳转至Projects列表路由(推荐)

既然api_v1_root指向的就是projects#index,直接使用明确的命名路由更清晰,且避免方法冲突:

def destroy
  project = Project.find(params[:id])
  project.destroy

  redirect_to api_v1_projects_path, status: :see_other
end

方案2:使用命名空间Root路由并强制GET方法

若坚持使用api_v1_root,需在重定向时指定使用GET方法,覆盖原请求的DELETE方法:

def destroy
  project = Project.find(params[:id])
  project.destroy

  redirect_to api_v1_root_path, status: :see_other, method: :get
end

方案3:符合REST规范的API处理方式(更优)

对于API接口,通常无需页面跳转,直接返回204 No Content状态码更符合REST设计:

def destroy
  project = Project.find(params[:id])
  project.destroy

  head :no_content
end

内容的提问来源于stack exchange,提问作者Kevin B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:23:22