如何在不覆盖路径的情况下在资源内部创建自定义路由

How to create a custom route inside resource without overwrite path

我在 routes.rb

resources :questions, except: [:show] do
   get '/resource/:subject/:id', to: 'resource#show', as: "resource", param: [:name, :id]

上面写着:

Invalid route name, already in use: ‘resource' You may have defined two routes with the same name using the :as option, or you may be overriding a route already defined by a resource with the same naming

我知道资源创建了两个具有相同路径的路由,showdestroy 都使用 resource_path,它是如何在内部创建的?以及如何在不覆盖销毁路线的情况下生成我的表演路线?

我觉得你可以把show拿出来,然后单独定义你想要的路线。看看这是否有效:

resources :questions, except: :show

get '/resource/:subject/:id',
  to: 'resource#show',
  as: "resource",  # This is where the error is.
  param: [:name, :id]

编辑:啊,是的。 :as 参数需要不同的名称。这将起作用:

resources :questions, except: :show

get '/resource/:subject/:id',
  to: 'resource#show',
  as: "resource_show",
  param: [:name, :id]

消除不需要的路由的一个好方法是指定 :only 选项

resources :user, :only => [:edit] 

而不是

resources :user, :except => [:new, :create, :edit, :update, :show, :destroy]