Rails: Using CanCan to assign multiple roles to Users for each organization they belong to?

authorization, cancan, ruby-on-rails, ruby-on-rails-3, rubygems

Solution

You're thinking that you have to save roles as a string field in the User model. You don't have to, at all:

class User
  has_many :roles
end

class Role
  belongs_to :user
  belongs_to :organization
  attr_accessible :level
end

class Ability
  def initialize(user)
    can :read, Organization
    can :manage, Organization do |organization|
      user.roles.where(organization_id:organization.id,level:'admin').length > 0
    end
    can :write, Organization do |organization|
      user.roles.where(organization_id:organization.id,level:'member').length > 0
    end
  end
end

Problem

A User can belong to many Organizations. I would like User to be able to be assigned different roles/authorizations for each of the organization it belongs to. For example, user "kevin" may belong to organization "stackoverflow" and "facebook." kevin should be able to be an admin for stackoverflow, and a regular member(read+write) for facebook. However, the CanCan gem only seems to address user roles for a single organization. I'm still a beginner, but from what I can gather, the CanCan gem assumes user roles are tied only to the main app. How would I be able to assign separate roles for different organizations, preferably using the CanCan gem?

Original source