views:

301

answers:

3

What is the typical format/structure for creating an administrative area in a Rails application?

Specifically I am stumped in the vicinity of these topics:

  • How do you deal with situations where a model's resources are available to both the public and the Admin? i.e. A User model where anyone can create users, login, etc but only the admin can view users, delete/update them, etc.
  • What is the proper convention for routing?
  • How does one structure controllers?
  • Are duplicate controllers considered OK? i.e. An admin version and the non-admin version?

Thank you!

+2  A: 

You can have 2 controllers, one for the public part and other for the admin and use admin namespacing:

map.namespace(:admin, :path_prefix => 'settings', :name_prefix => 'admin_') do |admin|
    admin.resources :users  
end

It would map to /settings/users and the controller would have to be prefixed by Admin:: like Admin::UsersController, also the controller file has to be put in an admin folder under the app/controllers dir.

  • Yes, if they make your code clearer, would be a big mess if for example you had the same controller for admin and public views, which then have to render different view templates based on if an admin or normal user accesses them. Also see here for more information.
Tõnis M
Damien, thanks for answering.Question on the second point RE routing. How does this impact your usage of the controller generators? ANDDo you scaffold at all?
Carb
You can scope the controller generation as well... `script/generate controller admin/users`.
Aaron Hinni
A: 

In addition to setting up an admin namespace in my routes, I use the declarative_authorization plugin, which lets you define roles for users and define access controls on controller actions as well as model attributes. If a user tries to access an action that don't have permission for, the plugin will redirect their request. Really neat way of handling it and helps provide a granular level of security.

There are several other plugins in the Rails ecosystem that offer similar functionality.

Toby Hede
A: 

There's a series of Railscasts that shows an approach which avoids having a separate admin area by using conditionals in the views and controllers: Where Administration Goes.

This might not be suitable for your use case, but it's worth a look.

Stuart Ellis