Rails /新路径解释为 ID

Rails /new path interpreted as ID

我有一个控制器,其路由定义为:

resources :items, except: [:new, :edit]

以及 newedit 操作未在控制器中定义。

当我浏览到 /items/new 时,我从数据库中收到一条错误消息,指出找不到该项目。

并且参数包含{"id"=>"new"},从中我了解到路径的new部分被解释为id。

如何使 /items/new 路由失败?

您可以在路线的 :id 段上使用约束条件。

如果您知道 id 将永远是一个数字,请尝试使用:

resources :items, except: [:new, :edit], constraints: { id: /\d+/ }

这将防止任何与 /\d+/ 正则表达式不匹配的内容(即一位或几位数字)被视为 id 值,从而防止路由与 /items/new

您可以简单地在您的控制器中执行此操作,通过渲染视图来避免它失败

 class ItemsController < ApplicationController
   rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

    def record_not_found
     render 'record_not_found'
     #do the other stuff
      true
    end
  end