1

I have the following relations:

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

class Analysis < ActiveRecord::Base
  belongs_to :patient
end

To use scopes in Patient is simple, I just did:

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

But how can I use do it to get all the analysis that only belongs to one specific patient using the resolve method?

Right now my analysis_policy look like this:

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

And the index action in AnalysesController:

  def index
    @analyses = @patient.analyses
  end

  ...
  private

  def set_patient
    @patient = Patient.find(params[:patient_id])
  end
Mario
  • 1,213
  • 2
  • 12
  • 37

1 Answers1

0

Analysis.joins(:patient).where(patient: { user_id: user.id }) should work. It might be where(patients: { user_id: user.id }) I can't remember. So as a scope on Analysis it'd be

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

So then you'd use Analysis.for_user(user.id)

j-dexx
  • 10,286
  • 3
  • 23
  • 36