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

时间:2010-12-11 05:59:05

标签: ruby-on-rails activerecord many-to-many 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

我如何创建和删除约会?

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

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

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

1 个答案:

答案 0 :(得分:7)

在创建约会的代码中,不需要第二行,并使用#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