如何通过连接表填充has_many中的字段

Gna*_*gno 8 activerecord ruby-on-rails has-many-through

我有一个关于活动记录关联的问题,请参考rails文档的这一部分:

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

如果我们有三个型号:

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)

文档说可以通过api以这种方式管理连接模型的集合:

physician.patients = patients
Run Code Online (Sandbox Code Playgroud)

但是,如果约会模型(如链接示例中)有一个名为appointment_date的字段,并且我想在特定日期为医生和患者创建新约会,该怎么办?以下代码将在约会表中创建一条记录,但是如何在第三步中填充appointment_date呢?

physician = Physician.first
patient = Patients.first
physician.patients << patient
Run Code Online (Sandbox Code Playgroud)

这样的事情存在吗?

physician.patients.create( :patient => patient, 'appointment.appointment_time' => appointment_time ) 
Run Code Online (Sandbox Code Playgroud)

sbe*_*eam 6

老问题,但应该回答 - 尽管您可以使用physician.patients<<方法直接分配,但它会创建一个没有值的约会,该约会可能有效也可能无效,具体取决于业务规则。因此,创建关联的更常见方法是在其中之一上建立约会

demento = Physician.find_by_name('Dr. Demento'}
patient = Patient.new { :name => 'Mrs. Holloway' }
patient.appointments << Appointment.new { :physician => demento, :appointment_time => appt_time }
Run Code Online (Sandbox Code Playgroud)

当然,如果你愿意的话,你可以将第 2 行和第 3 行结合起来。

您引用的文档中的行

physician.patients = patients
Run Code Online (Sandbox Code Playgroud)

我认为狭隘的用例可能是,如果德门托有 7 名患者,但由于死亡射线实验的不幸事件而失去了霍洛威夫人,那么您可以使用 6 名现有患者的更新列表来做到这一点,他们的预约将保存下来,霍洛威夫人过去的约会将被自动删除(为了删除这里的任何记录,出于责任保险的原因?只有德门托才会如此卑鄙)。