命名空间中的 Rails 路由资源以参数开头

问题描述:

我有 2 个命名空间,api 和 v1我有帐户和用户作为资源.

I have 2 namespaces, api and v1 I have accounts and users as resources.

我想为我的所有资源映射如下路由:

I want to map the routing as follows for all my resources:

/api/v1/:account_id/:resource/:id

/api/v1/:account_id/:resource/:id

即:/api/v1/1/users/2

i.e: /api/v1/1/users/2

在示例中,1 代表帐户 ID,2 代表用户 ID.

In the example 1 stands for account id and 2 stands for user id.

我该如何实现?

这消除了命名空间,因此您不需要将 API::V1:: 附加到每个控制器,或者将视图文件埋在子目录中.以下使用普通的顶级控制器和视图:

This does away with namespaces, such that you don't need to append API::V1:: to each controller, or bury view files in subdirectories. The following uses normal, top-level controllers and views:

scope '/api/v1/:id', :as => 'account' do
  resources :users
end

如果您想保留所有命名空间结构的内容,请执行以下操作:

If you want to keep all the namespace structure stuff, do this:

namespace 'api' do
  namespace 'v1' do
    scope '/:id', :as => 'account' do
      resources :users
    end
  end
end