2012-02-02 60 views
0

我目前正在使用設計和cancan項目。CanCan has_many通過,具體的能力

理解我的問題,我有這個型號:

用戶一些屬性和is_admin布爾全球訪問

角色 belongs_to的項目和用戶與特定能力的用戶對每個項目

項目 has_many一些其他模型用戶可以編輯或不可以(取決於它在項目上的作用)

所以我的問題是我該如何做到這一點?

其實我有這個能力類:

class Ability 
    include CanCan::Ability 
    def initialize(user) 
    if user 
     can :read, :all     # allow everyone to read everything 
     if user.is_admin? 
     can :manage, :all 
     end 
    end 
    end 
end 

我需要模型來管理的作用依賴於我的項目模型或其他什麼東西? 預先感謝您。

回答

2
class Ability 
    include CanCan::Ability 
    def initialize(user) 
    if user 
     can :read, :all     # allow everyone to read everything 
     if user.is_admin? 
     can :manage, :all 
     end 
     can manage, Project do |project| 
      project.users.include? user 
      #projects.users return the list of the users in the the role table. 
     end 
    end 
    end 
end 

您可以自定義它,但我認爲這是開始的好方法。

+0

難道沒有辦法像'can:manage,Project,:user_ids => user.id'嗎? – jackyalcine 2012-08-20 15:53:53

+0

我想你可以用「user_ids.include?user.id」代替行「project.users.include?user」 – Antoine 2012-08-20 20:45:34

+0

聽起來很聰明,我會試試看。 – jackyalcine 2012-08-21 18:09:25

1

下面是組織您的Ability.rb的更簡潔的方法。

def initialize(user) 
    user ||= User.new # Set user to blank User.new if user isn't logged in. 

    # Everyone, including guests, can read everything 
    can :read, :all 

    # Will only let user manage if @project.admin_id == user.id 
    can :manage, Project, admin_id: user.id 

end