Rails 路由:带有变量的命名空间

Rails Routes: Namespace with Variables

我有一个命名空间在 api:

中的资源
namespace :api, defaults: { format: :json } do
  resources :thing
end

(结果:/api/thing/:id

我想在 url 中为非资源 ID 变量添加另一个变量:

/api/non_resource/:non_resource_id/thing/:id

如何将 :non_resource_id 变量(以及 url 的关联 non_resource/ 部分)添加到命名空间?

事实证明,答案是向命名空间内的资源添加自定义路径前缀,而不是命名空间本身:

namespace :api, defaults: { format: :json } do
  resources :thing, path: '/non_resource/:non_resource_id/things'
end

这会在所有出现的资源 URL 前加上字符串(包括末尾的 things,因为这会覆盖默认值 /things)并允许访问 :non_resource_id 变量通过 thing 控制器中的 params 变量。

您可以使用 scope:

namespace :api, defaults: { format: :json } do

  scope '/non_resource/:non_resource_id' do
    resources :thing
    # other resources
  end

end