【问题标题】:Rails + Rolify: Singleton Pattern / Only one Role per User per ResourceRails + Rolify:单例模式/每个资源每个用户只有一个角色
【发布时间】:2015-08-22 22:49:39
【问题描述】:

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

在我的例子中,对于一个特定的资源,用户只能同时拥有一个角色。这意味着,在我做之前

user.add_role :lead, @resource

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

user.current_role.remove @resource

不存在。我只能遍历所有可能存在的角色,检查它是否存在并删除它。这对我来说听起来很丑陋。类似的东西

user.roles = []

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

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

提前感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails 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
    

    【讨论】:

      【解决方案2】:

      我最终想要一个更实质性的解决方案,从资源中删除各种角色。我用它做了一个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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-01
        • 2019-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多