rubyruby
rubyruby

Reputation: 21

multiple roles in rails

I want to design a role based system like Basecamp. A user can be editor of a brand and also he can be a worker in another brand. I'm using devise + cancan. How can i design a database for this situation? Thanks.

Upvotes: 2

Views: 770

Answers (2)

Austin Lin
Austin Lin

Reputation: 2564

I would recommend a role model. In this scenario a user would have_and_belong_to_many :roles while a role would have_and_belong_to_many :users. This creates a many to many relationship between roles and users. See this RailsGuide for more info on associations.

In your CanCan ability.rb file you can do something like this (I am just guessing at your setup):

 can :manage, Brand do |brand|
  user.has_role?("brand_manager") && user.brands.include?(brand)
end

In your user.rb file it's helpful to write something like this:

def has_role?(name)
  role = Role.find_by_name(name)
  (self.roles.include?(role)) ? (return true) : (return false)
end

Hope this helps.

Upvotes: 2

abm
abm

Reputation:

acl_system2. Its an old plugin, but checkout its readme file to see if it serves the purpose.

Upvotes: 0

Related Questions