rails 3: layout for namespaced routes rails 3: layout for namespaced routes ruby-on-rails ruby-on-rails

rails 3: layout for namespaced routes


I usually have a Base controller class in my namespace, and then have all controllers in that namespace inherit from it. That allows me to put common, namespace specific code in Base and all the controllers in that namespace can take advantage. For example:

class Admin::BaseController < ApplicationController  layout 'admin'  before_filter :require_admin_userendclass Admin::WidgetsController < Admin::BaseController  # inherits the 'admin' layout and requires an admin userend


Generally speaking, Rails will use the application layout if there isn't a layout that matches the controller. For example, if you had a PeopleController, Rails would look for layouts/people.html.erb and if it didn't find that, application.html.erb.

You can explicitly specify a specific layout if you want to override this convention.

class Admin::PeopleController  layout 'some_layout'end

That controller will then use some_layout.html.erb rather than looking for people.html.erb and application.html.erb.

But this might be a better way if you're looking to group things: If you have a base AdminController that inherits from ApplicationController, you can have your, say, Admin::PersonController inherit from the AdminController and it will inherit the admin layout.

I don't know the specifics of your code, but you might have:

class AdminController  def show    #render a template linking to all the admin stuff  endendapp/controllers/admin/people_controller.rb:class Admin::PeopleController < AdminController  #your awesome restful actions in here!endviews/layouts/admin.html.erb:Hello from the Admin!<%= yield %>

The one thing to realize is that Admin::PeopleController will inherit any actions that AdminController has defined (just as anything defined in ApplicationController becomes available in all sub-classes). This isn't generally a problem since you'll likely be overwriting the methods anyway, but just to be aware of it. If you don't have an AdminController, you can make one with no actions just for the purposes of the layout.