3

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?

4

2 回答 2

1

Ju Liu's answer worked, also adding

has_one :department, :through => :user

to the Offer model and using my original definition of

can :manage, Offer, :department => { :id => user.department_id}

seems to do the trick.

于 2013-06-26T10:03:03.410 回答
0

Something like this should work

can :manage, Offer do |offer|
  offer.user.department == user.department
end
于 2013-06-26T09:47:22.077 回答