2014-05-07 68 views
2

目前,我有以下情況:CanCanCan權限

  • 一個企業有很多項目
  • 一個企業擁有衆多用戶
  • 一個項目有許多用戶
  • 一個用戶不同項目上的許多角色

這是使用表Assignment進行建模的,該表具有project_id,role_id, 用戶名。

有四個角色:管理員,觀察者,用戶,訪客。

我想根據我對某個項目的角色給予權限,但是CanCan只接收我的用戶而不是我正在站立的項目,所以我不知道如何根據用戶只。

這是我當前的代碼,這是defenitely不正確的,但它已經爲現在。

def initialize(user) 

user ||= User.new # guest user (not logged in) 
if user.admin? 
    can :manage, :all 
else 
    can [:activate], User 
    can [:show,:index,:project_summary, :add_stage],Project 
    # only if the user is logged in 
    if user.id!=nil 
     can [:create,:update,:edit],Project do |p| 
      (user.assignments.where(project_id: p.id,role_id: 1,user_id: user.id).any? || user.assignments.where(role_id: 1,user_id: user.id).any?) 
     end 
     can [:show,:update, :add_user], Enterprise do |e| 
      user.assignments.where(role_id: 1,user_id: user.id).any? 
     end 
     can [:show],Enterprise do |e| 
      user.enterprise.id==e.id 
     end 
     # can only update if its his own 
     can [:show,:edit, :update], User, id: user.id 
    end 
end 

的問題是,現在我想給有能力的一個項目,以給新用戶添加到項目(這意味着創建一個分配)的「管理員」,如果我知道這才能實現我正站在哪個項目以及我的用戶。

如果有人可以幫助我,並解釋我是如何才能做到這一點有「三級跳」的關係(項目 - 用戶 - 角色),我會很感激。

謝謝!

回答

2

您需要根據用戶和項目驗證角色。所以你需要覆蓋ApplicationController中的能力方法,或者從其他需要權限的控制器中進行設置。

def current_ability 
    @current_ability ||= Ability.new(current_user, params[:project_id]) // Or params[:id] 
    end 

你可以做類似上面的事情。

然後你可以從這裏

Assignment.find_by(user.id: self.id, project.id: project_id).role.name 

贏得角色如果你有在作用方式的名稱。