角色继承与散列cancancan条件 - Role inheritance in cancancan with hash conditions

- 此内容更新于:2016-02-02
主题:

我做Rails4.2应用程序与CanCanCan宝石。我有我的能力。rb类。我做独立作用模型中解释宝石文档和角色继承解释。基本上每个角色是一个被调用的方法我想user.role。每一块。我不了解它是什么。我需要的是能够访问用户变量方法在def端例子里面的角色。让用户全球解决方案。或者有什么好的解决方案吗?

原文:

I am doing Rails 4.2 app with CanCanCan gem. I have my ability.rb class. I am doing separate role model as explained in gem docs and a role inheritance as explained too.

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

Basically each role is a method which gets called I suppose in user.role.each block. I do not understand fully what it does. What i need is to be able access user variable inside role methods as in def client example. Is making user global a solution. Or are there any good solutions?

解决方案:
简单的方法…你可以在这里阅读更多。
原文:

Simplest way...

#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

You can read more here.

网友:但我使用单独的角色模型,使用许多许多协会的角色。我想让角色继承文档中描述。

(原文:But I use separate role model where I use many to many association for roles. And I want role inheritance as described in docs.)

网友:这些文档你在说什么?

(原文:Which docs are you talking about?)

解决方案:
我解决了我的问题。我添加了用户作为参数发送:和添加方法:然后我做的:我告诉客户可以阅读任何病人,他拥有。
原文:

Ok I solved my problem this way. I added user as a parameter to send:

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

and added method:

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

And then I do:

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

  end

So I am telling that client can read any patient that he owns.