2015-08-22 71 views
1

我目前正在使用Rolify gem在我的Rails應用程序中設置我的角色管理 - 兩者均使用最新版本。Rails + Rolify:Singleton模式/每個用戶每個資源只有一個角色

就我而言,用戶只能同時擁有一個特定資源的角色。這意味着,在我做之前

user.add_role :lead, @resource 

我想刪除所有可能已經存在的角色。不幸的是像

user.current_role.remove @resource 

不存在。我只能循環所有可能存在的角色,檢查它是否存在並刪除它。這聽起來很醜陋。東西像

user.roles = [] 

並沒有幫助我,因爲我想刪除特定資源的所有角色。

rolify中是否有任何標準功能來支持這樣的事情?

感謝您的幫助提前!

回答

1

回覆救援的方法!

class User < ActiveRecord::Base 
    rolify before_add: :before_add_method 

    def before_add_method(role) 
    # do something before it gets added 
    end 
end 
-1

我最終想要一個更實質的解決方案,從資源中刪除各種角色。我做了一個gist出來的:

user.rb

class User < ApplicationRecord 
    rolify :strict => true, :before_add => :before_add_role 

    #Helper method to remove any existing role this user has for a resource 
    def remove_all_roles resource 
    # README: This syntax relies on changes on the following PR 
    # https://github.com/RolifyCommunity/rolify/pull/427 
    # Or include the source of this directly: 
    # gem 'rolify', :git => "git://github.com/Genkilabs/rolify.git" 
     remove_role nil, resource 
    end 

protected 

    #ensure that we only have a single role per resource 
    def before_add_role(role) 
     if role.resource 
      Rails.logger.debug "User::before_add_role: Adding the role of #{role.name} for #{role.resource_type} #{role.resource_id} to user #{id}" 
      #remove any pre-existing role this user has to the resource 
      remove_all_roles role.resource 
     end 
    end 
end 
相關問題