I have the following model :
class Member
belongs_to :enterprise
class Enterprise
has_many :members
has_many :enterprise_projects
has_many :projects, through: :enterprise_projects
class Project
has_many :enterprise_projects
has_many :projects, through: :enterprise_projects
class EnterpriseProject
belongs_to :project
belongs_to :enterprise
I also have the following permissions defined in ability.rb
class Ability
include CanCan::Ability
def initialize(user)
can :manage, Enterprise, members: { id: user.id }
can :manage, Project, enterprises: { members: { id: user.id } }
end
Combined with the following ProjectsController :
class ProjectsController < ApiController
load_resource :enterprise, through: :current_member, singleton: true
load_resource except: :create
authorize_resource
def index
render json: @projects
end
def create
project = Project.create(create_params)
@enterprise.enterprise_projects.create!(project: project)
project.save!
render json: project
end
Which allows me to restrict restrict the management of projects from a member to only projects associated to its enterprise. (and a project created by a member will be attached to its enterprise). However, if a member fetches a project, the enterprises attribute of the serialized object comprises all the enterprises attached to the project, but I would like it to be only the list of enterprises the member has access to (in this case it would be only one since member belongs to one company).
How can this be achieved ?