簡體   English   中英

Cancan rolize:根據角色定義資源能力

[英]Cancan rolify : Define abilty on resource depending on role

我想知道他們是否是使用cancan根據特定資源的角色定義能力的一種方式。

現在,我有這樣的事情,但是問題是,它遍歷了用戶每次擁有的每個角色,例如,即使在不同的Stuff實例上,角色也具有兩倍的角色。

def initialize(user)
    @user = user || User.new
    @user.roles.map(&:name).each{|name| send(name)}
  end

 def role1
    can :manage, Stuff
 end

我該如何優化呢?

我考慮過類似的事情:

def initialize(user)
    @user = user || User.new

     can :manage, Object do |object|
       roles = @user.roles.where(resource_id: object.id, resource_type: object.class)
       unless roles.empty?
         roles.map(&:name).each{|name| send(name)}
       end
     end
  end

但這仍然存在使“:manage”操作對資源上具有任何其他功能的任何用戶的問題。

那么,他們是否可以通過cancan的initialize函數訪問資源實例?

我發現了一些避免使用此問題的:manage的方法https://github.com/ryanb/cancan/issues/133

所以我加了

  def current_ability
    @current_ability = Ability.new(current_user, @resource)
  end

在控制器中的application_controller.rb中,在“授權!”之前 調用我已經定義了一個名為@resource的實例變量

像這樣:

def create
    project = Project.find(params[:project_id])
    @resource = project
    authorize! :create_stories, project
    ....
 end

並更新了capability.rb

 def initialize(user, resource)
    @user = user || User.new

    roles = @user.roles.where(resource_id: resource.id, resource_type: resource.class)
    if roles.empty?
      false
    else
      roles.map(&:name).each{|name| send(name)}
    end
  end

  def role1
    can :go_and_make_coffee
  end

如果能幫助某人,請盡情享受

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM