命名空间中的 Rails 路由资源以参数开头 [英] Rails routing resource in namespace starting with a parameter

查看:40
本文介绍了命名空间中的 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

这篇关于命名空间中的 Rails 路由资源以参数开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆