Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

and the url would be (standard):

/locations/1/users
/locations/1/users/new
/locations/1/users/10/edit
...

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

Update

It works if I add:

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...

like image 978
fluxsaas Avatar asked Sep 28 '11 13:09

fluxsaas


3 Answers

If you want to use just that one route:

match 'locations/:location_id/users' => "locations/users#index"

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

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
like image 42
nowk Avatar answered Nov 13 '22 07:11

nowk


One can use modules to have nested routes with nested controllers:

resources :locations do
  scope module: :locations do
    resources :users
  end
end

$ rake routes

...
location_users GET /locations/:location_id/users locations/users#index
...
like image 191
Alex Avatar answered Nov 13 '22 05:11

Alex


Like Kwon says, it's the order that matters. But you can still use a namespace.

.../config/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
like image 5
pduey Avatar answered Nov 13 '22 07:11

pduey