如何通过连接表填充 has_many 中的字段 [英] How to populate fields in a has_many through join table

查看:15
本文介绍了如何通过连接表填充 has_many 中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a question concerning active record association, referring to this part of the rails documentation:

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

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

The documentation says that the collection of join models can be managed via the api this way:

physician.patients = patients

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

but what if the appointment model, like in the linked example, has a field called appointment_date and I want to create a new appointment given the Physician and the Patient at a specific date? The following code will create a record in the appointment table, but how to populate the appointment_date too in the third step?

physician = Physician.first
patient = Patients.first
physician.patients << patient

这样的东西存在吗?

physician.patients.create( :patient => patient, 'appointment.appointment_time' => appointment_time ) 

推荐答案

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

old question, but it should be answered - although you can assign directly to physician.patients with the << method, it creates an appointment with no values, which may or may not be valid depending on the business rules. So the more usual way to create the association would be to build the appointment on one of them

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

如果您愿意,当然可以合并第 2 行和第 3 行.

you could combine lines 2 and 3 of course if you are so inclined.

您参考的文档中的行

physician.patients = patients

我认为狭义的用例可能是,如果 Demento 有 7 名患者,但由于不幸的死亡射线实验事件而失去了霍洛威夫人,那么您可以使用 6 名现存患者的更新列表来执行此操作,并且他们的约会将被保留,Holloway 夫人过去的约会将被自动删除(为了消除这里的任何记录,出于责任保险的原因?只有 Demento 会如此卑鄙).

I think the narrow use case for that might be, if Demento had 7 patients but loses Mrs. Holloway due to an unfortunate incident with a death ray experiment, then you could do this with a updated list of the 6 extant patients and their appointments would be preserved, and Mrs. Holloway's past appointments would be automatically deleted (so as to erase any record of here, for liability insurance reasons? only Demento would be so dastardly).

这篇关于如何通过连接表填充 has_many 中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆