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

时间:2015-08-22 22:49:39

标签: ruby-on-rails rolify

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

就我而言,一个特定资源的用户只能同时拥有一个角色。这意味着,在我做之前

user.add_role :lead, @resource

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

user.current_role.remove @resource

不存在。我只能遍历所有可能存在的角色,检查它是否存在并删除它。这对我来说听起来很难看。像

这样的东西
user.roles = []

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

rolify中是否有任何标准功能可以支持这样的内容?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分: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 :(得分:-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