开发者

Rails-way of structuring admin/user/public controllers

开发者 https://www.devze.com 2023-01-06 08:51 出处:网络
A fictitious Rails app has the following resources: Photographers Images Comments A Photographer has many Images, that have many Comments

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 c开发者_开发技巧ontrollers? 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!


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号