[英]How to setup cancancan abilities
難以弄清楚如何用康康舞能力來設置我的不同角色。 我有一個“業務”模型,該模型具有許多用戶::owner,:manager或:employee。
我試圖首先確保,如果他們不屬於該企業,他們將看不到該企業的任何信息。 其次,我想根據功能角色來限制功能。
我想我可以在視圖中使用if語句並僅向他們顯示他們可以訪問的東西來做到這一點,但我想知道cancan是否有更好的方法
在你的capability.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:使用load_and_authorize_resource,它將自動檢查所有7條rails方法
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步:在每個方法中手動進行授權檢查
def show @business = Business.find(params[:id]) authorize! :read, @business end
絕對要讀康康的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語句,或者嘗試使用局部視圖使它們看起來都可口,或者檢查控制器並根據角色呈現不同的視圖,但是,某處必須有if語句。
最好的方法是始終使用“增量”權限。 考慮到cancancan已經從您的用戶無權使用Business
的假設開始,因此您可以根據用戶的角色為其授予“增量”權限。
一個例子是:
# give read access if they have any role related to the business
can :read, Business, users: { id: user.id }
# give write access if they are manager
can [:edit, :update], Business, business_users: { role: 'manager', user: { id: user.id } }
# give destroy permissions to owners
can [:destroy], Business, business_users: { role: 'owner', user: { id: user.id } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.