2013-06-26 29 views
3

我試圖解決以下問題:Rails的康康舞可以:管理所有優惠主持人屬於同一部門

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 

用戶類有角色的屬性。我希望主持人角色能夠管理與主持人具有相同department.id的所有用戶的所有商品。因此,到目前爲止,我已經想出了以下內容:

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 

但行

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

顯示所有的優惠,不僅是一個我所需要的。任何想法如何改變線?可能是優惠模式中的範圍?

+0

優惠和部門如何鏈接? –

+0

不是直接通過用戶模型:a = Offer.first; a.user.department_id爲我提供department.id – user700304

回答

0

像這樣的東西應該工作

can :manage, Offer do |offer| 
    offer.user.department == user.department 
end 
+0

thx,這個工作 – user700304

1

菊劉的回答工作,還加入

has_one :department, :through => :user 

的發售模式,用我原來的

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

定義似乎做訣竅。

相關問題