Moudy
Moudy

Reputation: 888

How to set a specific layout for all controllers within a class or module. (Rails 3)

I have the following controllers under a Admin class (or module?)

class Admin::PostsController < ApplicationController
  layout 'admin'
  # controller methods...
end

class Admin::CommentsController < ApplicationController
  layout 'admin'
  # controller methods...
end

How can I define the layout in one place for these controllers in the Admin class? Do I need to make a new file for the Admin class and define it there? I have a feeling it's some thing like this (tried but din't work).

class Admin < ApplicationController
 layout 'admin'
end

Currently all controllers scoped to the admin class are located 'app/controllers/admin/'. If I need to create the Admin class file should it be inside that folder as well or in the one above? Or is the solution super simple and am I over thinking it?

Upvotes: 17

Views: 20719

Answers (1)

muffinista
muffinista

Reputation: 6736

Try creating a BaseController class, like this, then extending your other controllers to use it:

class Admin::BaseController < ApplicationController
  layout 'admin'
end

Then you would have:

class Admin::PostsController < Admin::BaseController
  # controller methods...
end

Upvotes: 33

Related Questions