[Need advice for newbie] How to define structure of applications in case I have multiple user roles.

Hi,

I am really newbie in RoR, I am just reading this book. I am trying to make very simple application who should have 3 user roles (3 groups of many users). Each role should have different permission set (of course i have to implement some authentication mechanism first).

Administrators - Should have access to all data (create, edit, update, delete).

Editors - Should have access to all data which they created (create, edit, update, delete).

Viewers - Should have read access to all data anyone created.

I just scaffold-ed basic structure of application, did some changes, defined relations between models … Scaffold views and controllers have all actions for all data (Show, edit, update, delete). My question is:

  1. Should I move somewhere to dedicated place (like /admin) these scaffold-ed files and “lock” them only for administrators? Create different set of controllers and views for Editors and different set of controllers and views Viewers? Is this even possible?
  2. Should I use existing scaffold-ed controllers and views and make application logic inside (filtering out displaying Edit link is not good idea, users always can “gues” the correct edit URL even I do not show button for edit)?
  3. Is there best practice for such common situation? thanx a lot for your opinions

Pavel K.

The cancan gem is pretty good at this. You create an ability file where you list what a user can do. At its most basic it would be

class Ability   include CanCan::Ability   def initialize(user)     if user.admin?       can :manage, :all     elsif user.editor?        can :manage, Post, :user_id => user.id     end     can read, :all   end end

(You'd have to repeat the Post bit for other classes)

Then cancan gives you view helpers, for example you could do

<%= if can? :edit, @post %> # display link to edit here <% end %>

Last but not least your controllers need to also check that the user is authorized. Cancan provides a default before_filter you can use if you're just using the standard restful actions.

The cancan wiki has loads of examples.

With the above, authorization isn't a reason for splitting up your controllers. However you might still consider splitting your editing interface from the one for the general public - perhaps they will want to see different information, that goes beyond an edit link here and an delete link there. For example perhaps editors would find a concise, table based list of posts useful, whereas users want something prettier. That side of things is probably one you'll need to answer for yourself.

Fred

Hi, Thanx a lot I will check this gem and it’s ability. It is pretty cool I would not have to separate all controllers and views.

Pavel K.