Search code examples
ruby-on-railsblockrolescancancancancan

Rails, abilities with cancancan


I am using cancancan to define abilities for my demo restaurant app. Each restaurant has_many employees and each employee has user_id and role attributes. I would like to allow a user to edit a restaurant only if this restaurant has an employee with user_id as the current_user.id and his role is 'manager'. My problem is that this role could be given to a lot of employees and when I find them by

can :edit, Restaurant do |restaurant|
    restaurant.employees.where(role: 'Manager').id=user.id 
end

I would get an array of all managers and this code would not return true. Any ideas of how to implement this :? Thanks!


Solution

  • You're probably looking for something more like this:

    can :edit, Restaurant do |restaurant|
      restaurant.employees.where(role: 'Manager', user_id: user.id).exists?
    end