添加和删​​除has_many:through关系

从Rails协会指南中,他们使用has_many演示了多对多关系:通过如下:

class Physician  :appointments end class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end class Patient  :appointments end 

我如何创建和删除约会?

如果我有一个@physician ,我是否可以编写类似下面的内容来创建约会?

 @patient = @physician.patients.new params[:patient] @physician.patients << @patient @patient.save # Is this line needed? 

删除或销毁代码怎么样? 此外,如果在约会表中不再存在患者,它是否会被销毁?

在创建约会的代码中,不需要第二行,并使用#build方法而不是#new

 @patient = @physician.patients.build params[:patient] @patient.save # yes, it worked 

要破坏约会记录,你可以简单地找到它并销毁:

 @appo = @physician.appointments.find(1) @appo.destroy 

如果要销毁约会记录以及销毁患者,则需要将:dependency设置添加到has_many:

 class Patient < ActiveRecord::Base has_many :appointments has_many :physicians, :through => :appointments, :dependency => :destroy end