2012-02-02 75 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