Cancan nested_routes restrict acces to :index

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 01:49:12

问题


I have some problems with cancan and a nested routes.

I have this routes :

resources :companies do
   resources :projects
end

I have no problem with the abilities for Company model but for the Project model I want to deny the access to Project#index if they are not admin of the company.

The next code works :

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 

But how I can do :

can? :index, Project

I tried by renamed the method like that :

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

and use :

can? :index_projects, @company

But it doesn't work. Do you know how to do it?

Thanks.


回答1:


you need to use something like this in your ProjectsController:

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

and when you`ll try to access Projects#index CanCan will check abilities and deny or allow access according to user abilities

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

hope this is what you need =]



来源:https://stackoverflow.com/questions/9371781/cancan-nested-routes-restrict-acces-to-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!