/ Rails

Creating an Admin Controller in Rails

Why create an Admin Controller?

It is easy enough to use something like CanCanCan to implement authorization, so why then would you need a separate Admin Controller?

While CanCanCan provides a good base, adding an Admin Controller provides another layer of protection, as the routes you are trying to protect simply do not exist unless you are properly authenticated as an Admin.

It is easy to leave a route unprotected or make a mistake if your edit/create/update/destroy routes are in your public controllers, having an Admin Controller helps prevent mistakes.


1). Generate an Admin Controller using your preferred method (generate controller or manually), placed in a controllers/admin folder.
2). Create each individual controller that you want behind an admin link (e.g. if you are trying to protect the edit/update/destroy/create actions for an Items Controller, create a new Items Controller with those actions inside of your controllers/admin folder).
3). Remove the newly protected actions from the old Items Controller (the old controller should now only have the actions that are public facing such as show/index).
4). In your config/routes.rb file, namespace the admin routes that you want. example:

namespace :admin do
  get '', to: 'dashboard#index'
  resources :items, except: [:index]
    resources :items, only: [:index, :show]

leaving your other items routes outside of the namespace.

In this example, the following routes are created:

admin GET /admin(.:format)admin/dashboard#index
admin_items POST /admin/items(.:format) admin/items#create
new_admin_item GET /admin/items/new(.:format) admin/items#new
edit_admin_item GET /admin/items/:id/edit(.:format) admin/items#edit
admin_item GET /admin/items/:id(.:format) admin/items#show
PATCH /admin/items/:id(.:format) admin/items#update
PUT /admin/items/:id(.:format) admin/items#update
DELETE /admin/items/:id(.:format) admin/items#destroy
items GET /items(.:format) items#index

Sticking Points

1). Remember to customize the POST URL from your admin forms (e.g.):
<%= form_for(@item, :url => admin_item_path(@item) ) do |f| %>


Feel free to comment, any other sticking points you've found? Better ways to implement this?

Creating an Admin Controller in Rails
Share this