如何通过连接表填充has_many中的字段
我有一个关于活动记录关联的问题,请参考rails文档的这一部分:
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
如果我们有三个型号:
class Physician :appointments end class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end class Patient :appointments end
文档说可以通过api以这种方式管理连接模型的集合:
physician.patients = patients
但是,如果约会模型(如链接示例中)有一个名为appointment_date的字段,并且我想在特定日期为医生和患者创建新约会,该怎么办? 以下代码将在约会表中创建一条记录,但是如何在第三步中填充appointment_date呢?
physician = Physician.first patient = Patients.first physician.patients << patient
做这样的事情存在吗?
physician.patients.create( :patient => patient, 'appointment.appointment_time' => appointment_time )
旧的问题,但应该回答 – 虽然您可以使用<<
方法直接分配给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 }
如果你愿意的话,你当然可以将第2行和第3行结合起来。
您引用的文档中的行
physician.patients = patients
我认为狭隘的用例可能是,如果Demento有7名患者但由于不幸的死亡射线实验事件而失去了Holloway夫人,那么你可以用6名现存患者的最新名单来做到这一点,他们的任命将是保留,Holloway夫人过去的约会将被自动删除(以便删除此处的任何记录,出于责任保险的原因?只有Demento会如此卑鄙)。
您希望考虑嵌套路由,例如
resources :physicians do resource :patients end
您可以使用form_for(@physician, @patient)
和url像physician/1/patient/23
用于在医生的背景下更新患者。
- rails 3 / postgres – 如果不应用,则为字符串多长时间:模式中的限制
- 为什么ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:near“)”:语法错误:INSERT INTO“user_friendships”()VALUES()
- JOIN ON …和在ActiveRecord中加载关联时的条件
- ActiveRecord :: Base.transaction应该在哪里?
- Rails – SQL查询返回所有指定相关对象的对象(has_many through)
- Rails 3validation包含何时使用find(如何proc或lambda)
- ROR中3路habtm的自定义数据库条目
- 需要使用范围嵌套连接的ActiveRelation
- 活动模型禁止属性错误