Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how to have an /admin section, and then controllers within the admin section?

Tags:

I want to have a /admin section in my application, and have routes within this /admin section like:

www.example.com/admin/ (only certain users have acess to this section)

then have controllers in this section like:

/admin/users/{add, new, etc}

What are my options for something like this? (using rails 3)

like image 967
Blankman Avatar asked Dec 02 '10 04:12

Blankman


3 Answers

I prefer to do something similar to Todd's answer but slightly different. Rather than adding the before_filter to each controller related to Admin stuff I prefer to create an AdminController that all controllers related to admin actions can inherit from:

# config/routes.rb
namespace :admin do
  resources :users
end

# app/controllers/admin_controller.rb
class AdminController < ApplicationController
  before_filter :authorized?
  private
  def authorized?
    unless current_user.has_role? :admin
      flash[:error] = "You are not authorized to view that page."
      redirect_to root_path
    end
  end
end

# app/controllers/admin/users_controller.rb
class Admin::UsersController < AdminController
   ...
end
like image 76
stevenhaddox Avatar answered Oct 02 '22 14:10

stevenhaddox


Do something like this in your routes.rb:

  namespace :admin do
    resources :users
  end

See http://guides.rubyonrails.org/routing.html for more detail.

Then in each admin controller you'll need a before_filter:

before_filter :authorized?
def authorized?
    #check if authorized here.
end
like image 20
Todd Avatar answered Oct 02 '22 16:10

Todd


As Todd mentioned, you want to add a namespaced route:

namespace :admin do
  resources :users
end

You also need to put your controllers, views, etc in subfolders of each of these sections called "admin/". If you're generating this from scratch, it's easy:

rails g controller admin/users

This may seem pretty complicated, but I have an article that walks through all of this, with a sample rails 3 app you can download to play around with it:

Routing in Ruby on Rails 3

like image 37
Jaime Bellmyer Avatar answered Oct 02 '22 16:10

Jaime Bellmyer