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)
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With