Cancan nested_routes限制对:index的访问

我有一些cancan和嵌套路线的问题。

我有这条路线:

resources :companies do resources :projects end 

我对公司模型的能力没有任何问题,但对于项目模型,如果他们不是公司的管理员,我想拒绝访问Project#index。

下一个代码有效:

 can :show, Company do |company| if user.admins.include?(company) #check if the user is admin of the company can :index, Schedule, :company_id => company.id end end 

但我该怎么做:

 can? :index, Project 

我尝试重命名这样的方法:

 can :index_projects, Company do |company| if user.admins.include?(company) #check if the user is admin of the company can :index, Schedule, :company_id => company.id end end 

并使用:

 can? :index_projects, @company 

但它不起作用。 你知道怎么做吗?

谢谢。

你需要在ProjectsController中使用这样的东西:

 class ProjectsController < ApplicationController def index authorize! :index, Ability @projects = Project.order(:created_at) end end 

当你试图访问Projects#index时,CanCan将根据用户能力检查能力并拒绝或允许访问

prooflink https://github.com/ryanb/cancan/issues/209#issuecomment-609043

希望这是你需要的东西=]