设置和读取has_many:通过连接表数据

时间:2013-09-06 04:33:07

标签: ruby-on-rails activerecord

我们以association documentation

为例
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

我的问题是,假设Appointment模型有一个appointment_date字段,在与新医生和患者合作时,如何才能最优雅地设置它?

目前我的创作解决方案是,取而代之的

physician = Physician.new(...)
patient = Patient.new(...)
physician.patients < patient
physician.save

我用:

physician = Physician.new(...)
patient = Patient.new(...)
appointment = Appointment.new
appointment.physician = physician
appointment.patient = patient
appointment.appointment_date = Time.now
appointment.save

为了查询,我找到了following solution

是否有更短/更简洁/“Rails”的方式?

0 个答案:

没有答案