views:

781

answers:

3

I am working on my first Rails application and want to create an admin section.

Do I want to keep my views and controllers completely separate (that is, in separate directories) for the admin section and the rest of the site?

How can I organize my views/controllers in custom directories (how do I configure the routing)?

+5  A: 

To create your admin controllers:

script/generate controller admin/articles

Then in your routes.rb file

map.resource :admin do |admin|
  admin.resources :articles, :path_prefix => "admin", :name_prefix => "admin_", :controller => "admin/articles"
end

You could then access the index url for this:

<%= link_to "Articles Admin", admin_articles_path %>
railsninja
+3  A: 

You could also keep the apps and controllers in their usual places and use Rails filters to control access, which is what I think you're looking for here.

If you have the AWDWR Book handy, flip to Chap11 Task F Administrivia

  • Basically define an authorize method in app\controllers\application.rb, which checks authorization, redirects to login page if not logged in et.all
  • Mark controllers you want to restrict access to with before_filter s

.

class AdminController < ApplicationController
   before_filter :authorize
   #  ... the rest of the code
end

This will intercept all calls to actions defined in AdminController and force them to go via authorize

Gishu
Might this complicate routing? I also like the idea of having separate directories just to keep things more orderly.
Abi Noda
Not at all.. The beauty is that you don't have to define (or even mess with) different routes. Everything goes via a single path, the authorize before_filter ensures that only authorized requests get through to the protected actions.It's a 'declarative' approach..
Gishu
That approach is ok, but not always appropriate, especially if you want to have an almost CMS like admin section as opposed to a few admin resources littered through your application.
railsninja
+3  A: 
map.namespace :admin do |admin|
  admin.register :controller => 'main', :action => 'register'
  admin.login, :controller => 'main', action => 'login'
  # ...
end

This is how you namespace things, add this to the other comments here about authorizing things and you're away. Have a look at the restful_authentication plugin to do your user management, much quicker and easier than rolling your own.

The above routing assumes the controllers and their views are in a subdirectory called admin, which I think is what you want.

Ghoti