Rails + Rolify:单例模式/每个资源每个用户仅有一个角色

3

我目前正在使用最新版本的Rolify gem在我的Rails应用程序中设置角色管理。

在我的情况下,一个用户在同一时间只能拥有一个特定资源的角色。这意味着,在执行

user.add_role :lead, @resource

我想删除所有可能已经存在的角色。不幸的是,这样的操作可能会导致数据丢失。

user.current_role.remove @resource

不存在。我只能循环遍历所有可能存在的角色,检查它是否存在并将其删除。这听起来对我来说很丑陋。类似这样的事情。

user.roles = []

这对我也没有帮助,因为我想删除特定资源的所有角色。

在 rolify 中是否有任何标准功能来支持这样的操作?

提前感谢您的帮助!

2个回答

3
回调方法来拯救!
class User < ActiveRecord::Base
  rolify before_add: :before_add_method

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

0

最终我想要一个更实质性的解决方案,可以从资源中删除所有类型的角色。我把它做成了一个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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接