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

dte*_*eoh 5 activerecord many-to-many ruby-on-rails has-many-through

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

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

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

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end
Run Code Online (Sandbox Code Playgroud)

我如何创建和删除约会?

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

@patient = @physician.patients.new params[:patient]
@physician.patients << @patient
@patient.save # Is this line needed?
Run Code Online (Sandbox Code Playgroud)

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

Kev*_*vin 7

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

@patient = @physician.patients.build params[:patient]
@patient.save  # yes, it worked
Run Code Online (Sandbox Code Playgroud)

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

@appo = @physician.appointments.find(1)
@appo.destroy
Run Code Online (Sandbox Code Playgroud)

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

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments, :dependency => :destroy
end
Run Code Online (Sandbox Code Playgroud)