Search code examples
ruby-on-railscontrolleradminradix

Rails Base Controller for admin


Im migrating from .net to rails and im a beginner. I have played around but cant figure out how can i create a base controller for admin namespace to share some functionality. I mean, where to put the Base class because i get errors for each try.

Thanks


Solution

  • Assume that you are using Rails 3. You can do like this.

    routes.rb

    namespace :admin do
      resources :users
    end
    

    Here is the structure of controllers folder:

    controllers/
      application_controller.rb
      admin/
        base_admin_controller.rb
        users_controller.rb
    

    admin/base_admin_controller.rb:

    class Admin::BaseAdminController < ApplicationController
      protected
    
        def some_shared_method
          # Do something
        end
    end
    

    You can add any methods that all admin controllers will share. Then just simply inherit the BaseAdminController class.

    admin/users_controller.rb:

    class Admin::UsersController < Admin::BaseAdminController
      def index
        some_shared_method
      end
    end