Rails 4:通过关联删除has_many

时间:2014-04-28 22:36:16

标签: ruby-on-rails associations has-many

基于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不仅会删除关联,还会删除实例本身。

如何只删除关联?

2 个答案:

答案 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