Reputation: 587
I'm building a rails app that has two distinct resources that represent types of users - tenants and landlords.
I have authentication for both set up via Devise, and authorization for one of the resources using CanCan.
I do not want to make them types of the same user resource, because they have different relationships with the other resources in the app (a property belongs_to a landlord, but has_many tenants, for example).
I have found lots of info about how to set up Cancan for a single resource with multiple roles (a user with an admin role, for instance), but am coming up empty about how to handle authorization for multiple resources at the same time.
Can anyone point me in the right direction?
Upvotes: 0
Views: 886
Reputation: 19308
You can add a role
column to the users
table and populate this field with different roles.
$ rails generate migration AddRoleToUsers role:string
Update the models/ability.rb
file to customize the authorization:
class Ability
include CanCan::Ability
def initialize(user)
if user.nil?
can :read, :all
elsif user.role == "landlord"
can :manage, :all
elsif user.role == "tenant"
can :read, :all
can :create, ToDoList
can :update, ToDoList do |to_do_list|
to_do_list.user == user
end
can :destroy, ToDoList do |to_do_list|
to_do_list.user == user
end
end
end
end
Upvotes: 0
Reputation: 4575
ok from the top of my head, you can do something like this:
--models>>ability.rb:
class Ability
include CanCan::Ability
def initialize(user)
if user.class.name=='Landlord'
can :manage, :all
elif user.class.name=='Tenant'
can :read, :all
else
can :read, :all
end
end
end
Upvotes: 2