Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 routing with namespace

When trying to access the following URL, I get a 404 error page:

dev.mydomain.com/api

whereas my routes.rb file mentions that this route does exist:

routes.rb

constraints :subdomain => 'dev' do
  root :to => 'developers/main#index', :as => :developers
  namespace 'api', :as => :developers_api do
    root :to => 'developers/apidoc/main#index'
  end
end

rake routes

         developers   /(.:format)      {:subdomain=>"dev", :controller=>"developers/main", :action=>"index"}
developers_api_root   /api(.:format)   {:subdomain=>"dev", :controller=>"api/developers/apidoc/main", :action=>"index"}

controller

/app/controllers/developers/apidoc/main_controller.rb

class Developers::Apidoc::MainController < Developers::BaseController
  def index
  end
end

logs

[router]: GET dev.mydomain.com/api dyno=web.1 queue=0 wait=0ms service=14ms status=404 bytes=0
[web.1]: Started GET "/api"
[web.1]: ActionController::RoutingError (uninitialized constant Api::Developers)
like image 284
Arnaud Leymet Avatar asked Jul 22 '11 10:07

Arnaud Leymet


2 Answers

I'm guessing the problem is that your route points to api/developers/apidoc/main but your class is only Developers::Apidoc::MainController. You should either not namespace that route with api or add Api to the namespace of the controller - Api::Developers::Apidoc::MainController.

like image 74
pcg79 Avatar answered Sep 18 '22 11:09

pcg79


Another important factor to keep in mind is that route namespaces need accompanying directory paths to be consistent. Getting this wrong will also cause an error like this:

Routing Error

uninitialized constant Api::Developers

In my case, I had a route structure like this:

namespace "api" do
  namespace "developers" do
    ...
  end
end

and the folder/directory structure should have been app/controllers/api/developers/

like image 42
Excalibur Avatar answered Sep 20 '22 11:09

Excalibur