Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces with nested resources Rails 3.2.8

I'm trying to organize my Rails application into two namespaces that provide the same resources, but with different controllers and views. Something like the following cenario:

routes.rb

resources :beehives do
    resources :bees
    resources :honeycombs
end

namespace :api do
    resources :beehive, only: [:show] do
        resources :bees, only: [:index, :show]
        resources :honeycombs, only: [:index, :show]
    end
end

Using scaffold, I've created the controllers structure:

rails g controller api/beehives

rails g controller api/beehives/bees

rails g controller api/beehives/honeycombs

And the folder structure I got for controllers sounds like this:

+ app
  + controllers
    - beehives_controller.rb
    - bees_controller.rb
    - honeycombs_controller.rb
    + api
      - beehives_controller.rb
      + beehives
        - bees_controller.rb
        - honeycombs_controller.rb

controllers/beehives_controller.rb

class Api::BeehivesController < ApplicationController 

controllers/api/beehives_controller.rb

class Api::BeehivesController < ApplicationController 

controllers/api/beehives/bees_controller.rb

class Api::Beehives::BeesController < ApplicationController 

Well, that was easy. In this context, /beehives/1 will route to root namespace (intended for the web application) and /api/beehives/1 to the "api" namespace (intended for providing a RESTful webservice). That's working really fine. The problem is when I try to access /api/beehives/1/bees, for some reason, the namespacing is not applying to the nested resource and Rails spit this error:

uninitialized constant Api::BeesController

What I'm doing wrong?

like image 298
derekstavis Avatar asked Oct 11 '12 18:10

derekstavis


1 Answers

resources :beehive + nested resources :bees doesn't require your respective controllers to be nested too. It's just a way of constructing URLs. So, it's naturally that your app asks for Api::BeesController instead of Api::Beehives::BeesController.

If you have any doubts, use rake routes command to check your routes and their associated controllers.

like image 149
jdoe Avatar answered Oct 03 '22 18:10

jdoe