我想在子目录中组织我的控制器。这是一个例子:
routes.rb中:
resources :locations do
resources :users
end
我想将控制器放在适当的子目录中:
app/controllers/locations/users_controller.rb
,网址为(标准):
/locations/1/users
/locations/1/users/new
/locations/1/users/10/edit
...
如果我的路线中有命名空间,我可以将users_controller.rb更改为
class Locations::UsersController < LocationsController
end
但它不适用于嵌套资源,而是出现以下错误:
Routing Error
uninitialized constant UsersController
如果我添加:
resources :locations do
resources :users
end
match 'locations/:location_id/users' => "locations/users#index"
但我必须为每个操作和嵌套资源添加一个路由......
答案 0 :(得分:14)
如果您只想使用那条路线:
match 'locations/:location_id/users' => "locations/users#index"
应该在可能与该匹配相冲突的任何其他资源/匹配之前。默认情况下,Rails路由是自上而下的。
# should be before locations resource
resources :locations do
resources :users
end
或者,如果您想将所有嵌套users
资源转移到locations/users
,您可以将控制器分配给资源。
resources :locations do
resources :users, :controller => "locations/users"
end
答案 1 :(得分:9)
可以使用模块来嵌套带有嵌套控制器的路径:
resources :locations do
scope module: :locations do
resources :users
end
end
$ rake routes
...
location_users GET /locations/:location_id/users locations/users#index
...
答案 2 :(得分:5)
... /配置/ routes.rb中
namespace :locations do
resources :users
end
resources :locations
... / app / controllers / locations_controller.rb:
class LocationController < ApplicationController
... / app / controllers / locations / users_controller.rb:
class Locations::UsersController < LocationsController