2017-07-18 215 views
0

无法确定如何使用cancancan功能设置我的不同角色。我有一个模型“商业”,其中有许多用户的角色是:所有者,:经理或:员工。
我试图让它首先,如果他们不属于该业务,他们不能看到任何业务。第二,我想根据他们拥有的角色限制功能。如何设置cancancan功能

我想我可以在视图中做到这一点,通过使用if语句,只向他们展示他们获得的东西,但不知道是否有与康康舞

+0

可以添加的代码你已经尝试并不起作用? – coorasse

回答

1
  • 您ability.rb

    class Ability 
        include CanCan::Ability 
    
        def initialize(user) 
        alias_action :create, :read, :update, :destroy, :to => :crud 
        if user 
         if user.role == "manager" 
          can :crud, Business, :id => user.business_id 
          # this will cek whether user can access business instance (id)  
         elsif user.role == "owner" 
          can :manage, :all 
         end 
        end 
        end 
    end 
    

控制器里面,你可以用2种方式

  1. 第1步做检查里面:与load_and_authorize_resource,这将自动检查所有7导轨法

    class BookingsController < ApplicationController 
        load_and_authorize_resource 
        # this before filter will automatically check between users and resource 
        # rails method here 
        def show 
        end 
    end 
    
  2. 步骤2:用授权手动检查各方法

    def show 
        @business = Business.find(params[:id]) 
        authorize! :read, @business 
    end 
    
0

通过cancan's wiki当然理解为我是一个更好的办法不是100%,但我认为该解决方案将是这个样子:

def initialize(user) 
    user ||= User.new 

    if user.has_role?(:owner) 
    can :read, Business, Business.all do |business| 
     business.id == user.business_id 
    end 
    elsif user.has_role?(:whatever) 
    # etc 
    end 
end 

然后,只需检查authorize!在正常康康舞方式的控制器。至于在视图中向他们展示适当的功能,你可以在视图中做一堆if语句,也许可以尝试使用partials来使其看起来很美味,或者检查控制器并根据角色呈现不同的视图,但是,如果在某处有声明就应该有。

0

的最佳方式内是始终使用 “增量” 的权限。考虑到cancancan已经启动,假设你的用户在Business上没有权利,所以你可以根据他们的角色为他们提供“增量”权限。

一个例子是: