基于Rails指南中的一个示例(http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association),我编写了以下代码:
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
问题在于,如果我有一个physician
(一个医生的实例)和一个patient
,那么
physician.add_vip(patient)
physician.delete_vip(patient)
delete_vip
不仅会删除关联,还会删除实例本身。
如何只删除关联?
答案 0 :(得分:1)
您要删除的关联/记录是约会而非患者。您正在add_vip
中创建约会,并且应该在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
答案 1 :(得分:0)
你可以这样做(不仅仅是):
def delete_vip patient
Appointment.where(physician_id: self.id, patient_id: patient.id).first.destroy!
end