在嵌套资源的子目录中分组控制器 [英] grouping controller in subdirectories for nested resources
问题描述
我想在子目录中组织我的控制器.下面是一个例子:
I would like to organize my controllers in subdirectories. Here is an example:
routes.rb:
resources :locations do
resources :users
end
我想将我的控制器放在适当的子目录中:
I would like to put my controller in the appropriate subdirectory:
app/controllers/locations/users_controller.rb
网址将是(标准):
/locations/1/users
/locations/1/users/new
/locations/1/users/10/edit
...
如果我的路由中有一个命名空间,我可以将我的 users_controller.rb 更改为
If i had a namespace in my routes I could change my users_controller.rb to
class Locations::UsersController < LocationsController
end
但它不适用于嵌套资源,而是出现以下错误:
but it does not work with nested resources, instead I get the following error:
Routing Error
uninitialized constant UsersController
更新
如果我添加:
resources :locations do
resources :users
end
match 'locations/:location_id/users' => "locations/users#index"
但我必须为每个操作和嵌套资源添加一个路由...
but I would have to add a route for every action and nested resource...
推荐答案
如果您只想使用那一条路线:
If you want to use just that one route:
match 'locations/:location_id/users' => "locations/users#index"
这应该出现在可能与该匹配项冲突的任何其他资源/匹配项之前.默认情况下,Rails 路由是自上而下的.
That should come before any other resources/matches that might conflict with that match. By default Rails routes are top-bottom.
# should be before locations resource
resources :locations do
resources :users
end
或者,如果您想将所有嵌套的 users
资源转移到 locations/users
,您可以为资源分配一个控制器.
Alternatively, if you want to punt all your nested users
resource over to locations/users
you can assign a controller to the resource.
resources :locations do
resources :users, :controller => "locations/users"
end
这篇关于在嵌套资源的子目录中分组控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!