0

我正在将 Refinery CMS 与扩展应用程序一起使用,该应用程序在其路由中具有以下内容:

namespace :sub_application do
  resources :employees
  resources :customers
  resources :yet_another_plural_resource
end

产生以下路线:

/sub_application/employees
/sub_application/employees/:emp_id
/sub_application/customers
/sub_application/customers/:cust_id
/sub_application/yet_another_plural_resource
.... (you get the picture)

现在,大多数用户将使用这些路线,但有些超级用户需要查看这些人正在查看的内容,就像他们查看内容一样。我对此的解决方案是通过路由系统将模拟的用户 ID 作为匹配变量传递,如下所示:

/sub_application/:user_id/employees
/sub_application/:user_id/employees/:emp_id
/sub_application/:user_id/customers
/sub_application/:user_id/customers/:cust_id
/sub_application/:user_id/yet_another_plural_resource
.... (you get the picture)

我需要在我的路由文件中添加什么,以便我可以同时拥有 :user_id 路由版本和常规版本?

4

1 回答 1

2

有点hack,但是您可以尝试使用“经典”嵌套资源,同时隐藏“用户”前缀。

namespace :sub_application do
  resources :employees
  resources :customers
  resources :yet_another_plural_resource

  # this block MUST be after the other routes
  # the empty path options should remove the 'users/' prefix
  resources :users, path: '' do 
    resources :employees
    resources :customers
    resources :yet_another_plural_resource  
  end
end

如果你想避免重复路线,你可以这样做:

namespace :sub_application do

  # store the routes in a lambda
  routes = ->{
    resources :employees
    resources :customers
    resources :yet_another_plural_resource
  }

  # apply the routes to current scope
  routes.call

  # then apply to nested resources scope
  resources :users, path: '', &routes
end

The routes will all lead to the same controllers, so you'll have to adapt your logic whether the request is made with or without an user_id.

If you do not want to route to a UsersController at all, just pass only: [] as an additional option to resources :users

EDIT

Actually, there is a simpler way than storing the routes in a lambda to make them available outside of nested scope :

namespace :sub_application do
  resources :users, path: '', shallow: true do
    resources :employees
    resources :customers
    resources :yet_another_plural_resource
  end
end

beware that it wont generate all routes by default. See the docs for more info.

于 2013-04-28T20:07:29.797 回答