【问题标题】:Scope for nested resources using pundit使用权威的嵌套资源的范围
【发布时间】:2016-02-11 08:57:20
【问题描述】:

我有以下关系:

class Patient < ActiveRecord::Base
  belongs_to :user
  has_many :analyses, dependent: :destroy
end

class Analysis < ActiveRecord::Base
  belongs_to :patient
end

在 Patient 中使用范围很简单,我只是这样做了:

  class Scope < Scope
    def resolve
      if user.admin?
        scope.all
      else
        scope.where(user_id: user.id)
      end
    end
  end

但是我如何使用 do it 来获取仅属于使用 resolve 方法的一个特定患者的所有分析?

现在我的 analysis_policy 如下所示:

class AnalysisPolicy < ApplicationPolicy

  def new?
    true
  end

  def edit?
    record.patient.user_id == user.id
  end

  alias_method :show?, :edit?
  alias_method :create?, :edit?
  alias_method :destroy?, :edit?
end

AnalysesController 中的 index 动作:

  def index
    @analyses = @patient.analyses
  end

  ...
  private

  def set_patient
    @patient = Patient.find(params[:patient_id])
  end

【问题讨论】:

    标签: ruby-on-rails authorization pundit


    【解决方案1】:

    Analysis.joins(:patient).where(patient: { user_id: user.id }) 应该可以工作。可能是where(patients: { user_id: user.id }) 我不记得了。因此,作为分析的范围,它会是

    class Analysis < ActiveRecord::Base
      belongs_to :patient
      scope :for_user ->(user_id) { joins(:patient).where(patient: { user_id: user_id })
    end
    

    那么你会使用Analysis.for_user(user.id)

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多