Alexandre
Alexandre

Reputation: 13308

Routing and namespaces in Ruby on Rails

A part of a code of a Ruby on Rails application:

    #routes.rb
        namespace :admin do
              root :to => 'admin#index'
              resources :orders, :products
        end

  #controllers/admin/admin_contrller.rb
    class Admin::AdminController < ApplicationController
       def index

       end
    end

The index view is located in views/admin/index.html.haml. However, it doesn't find it (http://localhost:3000/admin, missing template). It only finds it if it's located in views/admin/admin/index.html.haml.

What do I did wrong? What should I do to make it to find the view in views/admin/index.html.haml?

Upvotes: 1

Views: 2047

Answers (1)

Łukasz Strzałkowski
Łukasz Strzałkowski

Reputation: 408

You've created namespace :admin and put there root path and orders resource. Root path is pointed to index adction of AdminController. Having this configuration, rails will lookup for index.html.haml view under views/admin/admin/index.html.haml where first admin is namespace and second is controller's directory.

You did nothing wrong. It's just how rails work.

I would suggest, instead of trying to find the view in views/admin/index.html.haml to simply change AdminController name into DashboardController and creating BaseController as a base class for all controllers under admin/ directory.

app/controllers/admin/admin_controller.rb

class Admin::BaseController < ApplicationController
  #auth etc.
end

app/controllers/admin/dashboard_controller.rb

class Admin::DashboardController < Admin::BaseController

end

This way you'll easily add authentication, authorization, different layout etc. etc. and other stuff needed for admin controllers

But If you really want to sick with your solution, you can just simply do render admin/index in index action like this:

class Admin::AdminController < ApplicationController
  def index
    render "admin/index"
  end
end

Upvotes: 4

Related Questions