Travis Pessetto
Travis Pessetto

Reputation: 3298

CanCan authorize by id

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

user.rb

has_and_belongs_to_many :roles

roles.rb

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.

Pseudocode would look something like this:

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

Answers (1)

deefour
deefour

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

Related Questions