Performing calculation using attribute from joined table in scope

This is a rather contrived example (which does not work), but how would I go about using an attribute from a joined model in a scope after performing a calculation with it?

class Patient < ApplicationRecord
  belongs_to :doctor
  scope :eligible, -> {joins(doctor:[:clinic]).where("age >= ?", clinic.min_age - self.magic)}

  def magic
    10
  end
end

class Doctor < ApplicationRecord
  belongs_to :clinic
  has_many :patients
end

class Clinic < ApplicationRecord
  has_many :doctors

  def min_age
  	40
  end
end

This of course doesn’t work, and throws errors both on clinic.min_age and self.magic:

undefined local variable or method `clinic' for an instance of ActiveRecord::AssociationRelation

and

undefined method `magic' for an instance of ActiveRecord::AssociationRelation

I know that self in a scope doesn’t mean the same thing as it does in a model method; I just used it here to illustrate what I’m after. How should I write this scope?

I was able to solve this by moving the logic entirely into the DB query (I forgot how powerful PostgreSQL functions can be!) - but it would still be interesting to know how an AR scope (or class method) can perform calculations using attributes from members and then use those in a where clause.