【问题标题】:Role inheritance in cancancan with hash conditions带有哈希条件的cancancan中的角色继承
【发布时间】:2016-01-30 18:01:35
【问题描述】:

我正在使用 CanCanCan gem 开发 Rails 4.2 应用程序。我有我的能力.rb 课程。我正在按照 gem 文档中的说明进行单独的角色模型,并按照说明进行角色继承。

class Ability
  include CanCan::Ability

  def initialize(user)
      user ||= User.new # guest user (not logged in)
      user.roles.each { |role| send(role.name.downcase) }

  end

  # write down role permissions here

  def client
    can :manage, Client, :id => user.id
    can [:read,:create], Patient
  end

end

基本上每个角色都是我想在 user.role.each 块中调用的方法。我不完全理解它的作用。我需要的是能够访问角色方法中的用户变量,就像在 def 客户端示例中一样。使用户全球化是一种解决方案。或者有什么好的解决办法?

【问题讨论】:

    标签: ruby-on-rails ruby cancancan


    【解决方案1】:

    最简单的方法...

    #app/models/ability.rb
    class Ability
      include CanCan::Ability
    
      def initialize(user)
          user ||= User.new # guest user (not logged in)
          if user.role == "client"
             can :manage, Client, :id => user.id
             can [:read,:create], Patient
          elsif user.role == "x"
             ...
          end    
      end
    end
    

    你可以read more here

    【讨论】:

    • 但是我使用单独的角色模型,我使用多对多关联的角色。我想要文档中描述的角色继承。
    【解决方案2】:

    好的,我通过这种方式解决了我的问题。我添加了用户作为参数发送:

    user.roles.each { |role| send(role.name.downcase, user) }

    并添加方法:

    #ability.rb
    def any_patient?(client, id)
        client.patients.any? {|p| p.id == id }
    end

    然后我做:

    def client(user)
        can [:read], Patient do |patient|
          any_patient?(user.client, patient.id)
        end
    
      end

    所以我告诉客户可以读取他拥有的任何患者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      相关资源
      最近更新 更多