Multiple roles in Ruby On Rails

authorizationruby-on-railsusers

I've been asked to put together an application in RoR which has multiple roles for users. The idea is that a user will have a role, Admin, Moderator, User ect… and they will also have a department as well, HR, IT, Customer Care ect….

The app will have designated sections for each department to manage data and other basic CRUD based tasks.

What the app needs to allow is so a user can only access departments they are assigned to, a user can have multiple departments, a user can be a Admin of one department but may be only a user of another department.

Whats the best way of putting something like this together?

Best Answer

There is an n:m relationship between users and departments and another n:m relationship between users and roles. Each of these relationships could be represented by its own table in the DB. Assuming that each user object has an ID, you can query the database during the authorization to see whether an appropriate relationship exists. This could be checked by an authorization manager, but it would be good UX to not even display links to resources which an user is not authorized to use.

If you need to store this information inside your objects (which I'd rather not, because of the single-responsibility principle), each user would have a set of roles or departments. Each role/department would be a singleton object, so one could do (pseudocode:) user.roles.contains?(Role.admin).

Related Topic