I'm trying to solve the following problem:
class User < ActiveRecord::Base
belongs_to :department
has_many :offers
end
class Offer < ActiveRecord::Base
belongs_to :user
end
class Department < ActiveRecord::Base
has_many :users
end
The user class has an attribute of role. I want the :moderator role to be able to manage all Offers of all Users which have the same department.id as the :moderator. Thus far I've come up with the following:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.is? :admin
can :manage, :all
elsif user.is? :moderator
# Moderators can manage Users which belong to the same Department
can :manage, User, :department_id => user.department_id
# Moderators can manage all Offers which share the same department.id as the manager
can :manage, Offer, :department => { :id => user.department_id}
elsif user.is? :registered
# User can manage their own Offers
can :manage, Offer, :user_id => user.id
else
can :read, Offer
end
end
end
But the line
can :manage, Offer, :department => { :id => user.department_id}
shows all Offers, not only the one I need. Any idea how to change the line? Maybe a scope in the Offer model?