Search code examples
ruby-on-railsrubyauthorizationcancancancancan

Defining a complex ability using CanCanCan


In my data model:

Company has_many offices

Employee has_many offices, through: :employee_office (this is how I am allowing Company administrators to permission employees for certain offices and not others)

Office has_many appointments and Appointment belongs_to office

I would like to define an ability using CanCanCan that allows an Employee to perform actions on an Appointment only if the Employee works at the Office the Appointment was made at.

Something like this psuedocode:

Employee can :manage Appointment, Employee.offices.include?(Appointment.office)

This is what I have so far:

class EmployeeAbility
  include CanCan::Ability

  def initialize(employee)
    can :read,      Company,        :id => employee.company.id
    can :read,      Office,         :id => employee.company.id
    #I'd like to include the above psuedocode here, but I'm not sure how to structure it
  end
end

Thanks!


Solution

  • can :edit, Appointment, office_id: employee.office_ids