One of the most important parts of web development is building an administration back-end for your data, a place that is secure from the rest of your application where you can administrate users, topics, categories, or whatever you need for your website. But how do you do it in Ruby on Rails? Where do my controllers go? I will show you a simple way of creating an administration back-end for your Rails application.

Controllers

Firstly, create a sub-directory where all your administration controllers will be kept. Lets call this admin. The screen-shot below shows how I have stored a products controller for an application.

Each of the controllers inside the admin directory must be changed slightly to allow for Rails to locate them.

Class definitions need to be in the format of:

class (sub-directory-name)::ProductsController < ApplicationController

For example, the products controller the class definition will be:

# app/controllers/admin/products_controller.rb
class Admin::ProductsController < ApplicationController
  def index
    #index action
  end
end

Routing

Because you now have your admin controllers inside a sub-directory, a simple map.resources will not map your controllers correctly. Instead you will need to draw a map for your requests to the admin directory. To do this you will need to add the following code to your routes file. If you have any questions about routing have a look at the API for routing.

# config/routes.rb
ActionController::Routing::Routes.draw do |map|
  map.namespace :admin do |admin|
    admin.resources :products
  end
  # more
end

The above routing generates named routes for use in controllers and views. They are:

  • admin_products_url
  • admin_product_url(id)
  • new_admin_product_url
  • edit_admin_product_url

Views

So now you should have access to the products controller via http://servername/admin/products. Now we need to create a view for the products/index action. The views for the admin backend are also stored inside a sub-directory of views.

An example view for the admin products controller is below. Note the helpers used for routing and the admin_ prefix.

# app/views/admin/products/index.html.erb
<h1>List products</h1>
<% for product in @products %>
  <%= link_to product.name, edit_admin_product_url(product) %>
  <%= link_to "Delete", admin_product_url(product), :method => 'delete' %>
  <br/>
<% end%>
<%= link_to "Create", new_admin_product_url %>

Hopefully this tutorial helped you create an administration backend for your application. Please comment if you have any questions or advice! Thanks