title: has_many through association dependent destroy under condition of who called destroy
body: <p>Is there a way to check, within a <code>before_destroy</code> hook, what object (class) called <code>destroy</code>?</p>
  
  <p>In the following example, when a <code>patient</code> is destroyed, so are their <code>appointments</code> (which is what I want); however I don't want to allow a <code>physician</code> to be destroyed if there are any <code>appointments</code> associated with that <code>physician</code>.</p>
  
  <p>Again, is there a way to do such a check in the <code>before_destory</code> callback? If not, is there any other way to accomplish this "destruction check" based on the "direction" of the call (i.e. based on who called)?</p>
  
  <pre><code>class Physician &lt; ActiveRecord::Base
    has_many :appointments, dependent: :destroy
    has_many :patients, through: :appointments
  end
  
  
  class Patient &lt; ActiveRecord::Base
    has_many :appointments, dependent: :destroy
    has_many :physicians, through: :appointments
  end
  
  
  class Appointment &lt; ActiveRecord::Base
    belongs_to :patient
    belongs_to :physician
  
    before_destroy :ensure_not_referenced_by_anything_important
  
    private
  
    def ensure_not_referenced_by_anything_important
      unless patients.empty?
        errors.add(:base, 'This physician cannot be deleted because appointments exist.')
        false
      end
    end
  end
  </code></pre>