簡體   English   中英

Rails Cancan基於關聯被拒絕的授權

[英]Rails cancan authorization based on association being denied

我的ability.rb文件中包含以下代碼段:

def initialize(user)
  if user.group === 1
    can :manage, Task do |task|
      task.user.id === user.id
    end
  end 
end

用戶has_many任務,每個任務belongs_to用戶。 被請求的任務記錄(7)的user_id為4。發送請求的用戶的user_id為4。

在任務show方法中,我有以下代碼片段可授權並返回數據:

def show
    @task = Task.find(params[:id])

    authorize! :read, @current_user

    render json: @task, root: "task"
end

為什么會拒絕呢?

您需要授權任務,而不是current_user。 假設使用current_user:

def show
  @task = Task.find(params[:id])

  authorize! :read, @task

  render json: @task, root: "task"
end

在您的能力文件中,您可以這樣編寫:

def initialize(user)
  can :manage, Task do |task|
    task.user.id == user.id && user.group == 1
  end
end 

暫無
暫無

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

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