Rails可以扫描嵌套资源

时间:2010-10-22 05:51:18

标签: ruby-on-rails authorization cancan

我有项目资源,它嵌套在用户资源中。

我的Cancan Ability课程是:

class Ability
  include CanCan::Ability
  def initialize(user)
    #everyone
    can :read, Project

    if user.blank? 
      # guest user
      ...
    else
      #every signed in user

      case user.role
        when User::ROLES[:admin] 
          #only admin role user
          can :manage, :all

        when User::ROLES[:member] 
          #only member role user
          can :update, User, :id => user.id
          can [:create, :update, :destroy], Project, :user_id => user.id
        else

      end
    end
  end
end

And Projects控制器:

class ProjectsController < ApplicationController
  load_and_authorize_resource :user
  load_and_authorize_resource :projects, :through => :user, :shallow => true
  ...
end

我几乎没有问题:

是否有可能拒绝:读取用户并允许:阅读项目,以便每个人都可以访问/ users / 10 /项目,但不能访问/ users / 10或/ users?

如何拒绝用户访问:与其他user_id的新操作?例如,如果我添加

#everyone
can :read, User
can :read, Project

此代码允许id为42的用户访问/ user / 41 / projects / new。

1 个答案:

答案 0 :(得分:10)

通过以下方式解决:

class Ability
  include CanCan::Ability

  def initialize(user)
    #everyone
    can :read, Project

    can :read, User # required to access nested resources
    cannot :index, User
    cannot :show, User

    if user.blank? 
      # guest user
      ...
    else
      #every signed in user

      case user.role
        when User::ROLES[:admin] 
          #only admin role user
          can :manage, :all

        when User::ROLES[:member] 
          #only member role user
          can :update, User, :id => user.id
          can :manage, Project, :user => { :id => user.id }
        else

      end
    end
  end
end