1
votes

Based on one of the examples in the Rails Guides (http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association) I wrote the following code:

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments

  def vips
    patients.where(appointments: { vip: true })
  end

  def add_vip patient
    appointments.create(patient: patient, vip: true)
  end

  def delete_vip patient
    vips.delete(patient)
  end
end

The problem is that if I have a physician (an instance of Physician) and a patient and then do

physician.add_vip(patient)
physician.delete_vip(patient)

the delete_vip not only deletes the association but the instance itself.

How can I delete only the association?

2

2 Answers

1
votes

The association/record you want to delete is the Appointment not the Patient. You are creating an appointment in add_vip and should be removing an appointment in delete_vip.

# Deletes all appointments for that patient without destroying the patient itself.
def delete_vip patient
  appointments.where(patient: patient, vip: true).delete_all
end
0
votes

You can do it in this way (not only):

def delete_vip patient
    Appointment.where(physician_id: self.id, patient_id: patient.id).first.destroy!
end