-2

I want to setup a app where each user can have different roles inside a network.

So user A is an "admin" in network X, but also a "client" in network Y. Each role has his own capabilities inside the network. E.g. admin can create posts, client can only destroy his own comments etc.

What is the best table structure to achieve this setup? Should I use Devise + CanCan + ... setup?

Chiel
  • 1

1 Answers1

2

there's a gem called rolify (Role management library with resource scoping) gem, it can also be setup with devise and cancan link, let's assume that you have model User

installation:

gem "rolify"
bundle
rails g rolify:role Role User

you can add role:

user = User.find(1)
user.add_role :admin

check:

user.has_role? :admin

if you want to define a role scoped to a resource instance:

user = User.find(2)
user.add_role :moderator, Post.first

and in your ability.rb:

if user.has_role? :admin
  can :manage, :all
else
  can :read, Post
  can :write, Post, :id => Post.with_role(:moderator, user).map{ |f| f.id }
end

Note that the with_role method allows us to restrict the Post instances the user has a role on

Said Kaldybaev
  • 9,380
  • 8
  • 36
  • 53