Domanda

I'm currently building a Rails app and stuck with making a decision on how permissions schema needs to be implemented. I have a User model and a Project model. Each user can create one or more projects. At the same time user can be an admin or a guest in other projects. I'd like users to be able to see only those projects that they have created or were invited to.

I heard about CanCan gem, but couldn't figure out yet how to use it for my case. Can anyone advise how to do that? Thanks in advance!

È stato utile?

Soluzione

If you are new to Rails it is always good to try to implement something like auth at your own before moving to off-the-shelf solutions like devise + cancan. That being said it could be quite a challenge to roll you own role based auth.

What you could do in this specific example is connecting your users to your projects with a "many to many through" relation, thus allowing your relation itself have attributes like a regular model. http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

In your example you could do something like:

class User < ActiveRecord::Base
  has_many :appointments
  has_many :projects, through: :roles
end

class Role < ActiveRecord::Base

  # role might now have attributes like :admin, moderator 
  # or could specify individual permissions like :canread, :canwrite, :candelete
  # which you could check before allowing changes to projects. 

  belongs_to :user
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :roles
  has_many :users, through: :roles
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top