Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails-way of structuring admin/user/public controllers

A fictitious Rails app has the following resources:

Photographers
Images
Comments

A Photographer has many Images, that have many Comments

Each photographer has a login and is able to view, upload, edit and delete their images, comments as well as their own profile.

An administration interface is available and can edit both images, photographers and comments.

Furthermore, the photographer, their images and their comments are available from a public interface without login where visitors can add comments.

My question is: What is the Rails-way of structuring the controllers? I was thinking of going with namespaces for each 'role' (public, account, admin) like this:

# For administrator
Admin::PhotographersController
Admin::ImagesController
Admin::CommentsController

# For a logged in photographer
AccountController (?)
Account::ImagesController
Account::CommentsController

# For public
PhotographersController
ImagesController
CommentsController

However - some of the methods of these controllers are overlapping. Is this the best way, even though it's not that DRY?

Thanks!

like image 637
Mattias Avatar asked Jul 06 '10 13:07

Mattias


2 Answers

If they are overlapping, you could extend the base controllers into the account/admin namespaces. eg you do your ImagesController which is for the actions everyone can see. This extends ApplicationController as normal. Then you do your admin version of ImageController, and that extends ImagesController. Then you add/override methods in the admin version for the required different behaviours, or it may just be as simple as adding a couple of before filters such as require_admin for example, which checks that current_user is an admin user, and redirects them away if not.

like image 98
Max Williams Avatar answered Sep 24 '22 04:09

Max Williams


as you said, this is not really DRY. at least, you could structure routes and controllers to act for all the requirements, for example:

resources :photos, :only => [:index, :show] # offer only index and show actions to public 

scope "/admin" do
  resources :photos # full access for logged in users
end

if you also need index and show actions, you can add some checks inside them to load a different view (say you have a public and admin layouts).

another way could be to have a unique layout, no /admin/ sections and offer editing features to logged in users. so if logged and owner of some photo, allow editing and show context links. it's a matter of tastes :P

like image 27
Andrea Pavoni Avatar answered Sep 24 '22 04:09

Andrea Pavoni