Reputation: 3298
I have a many to many relationship in rails, a user has and belongs to many user_types and vice versa. Then user_type has many roles.
Example table for roles_fruits table:
role_id: 1, fruit_id: 6
Example for roles table:
id: 1, name: Bannana Worker
Example table for users:
id: 1, user_name: employee143
Example for fruits table:
id: 6, name: bananna
In the model
has_and_belongs_to_many :roles
has_and_belongs_to_many :users
Now, what I am trying to accomplish is to allow a user that has the role of "Bannana Worker" (id 1) to be able to get to it and those without it, not to be able to get into it.
if user.roles contains fruit id then can :manage, fruit
How can I accomplish this with cancan and if it isn't possible, what would be a good replacement gem?
Upvotes: 0
Views: 204
Reputation: 35360
Try something like this in ability.rb
can :manage Fruit do |fruit|
user.roles.exists?(fruit.id)
end
and in your controller you can do
def your_action
@fruit = ...
authorize! :manage, @fruit
# ...
end
Upvotes: 1