我正在关注RailsGuides tutorial,试图了解与联接表的关联。
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
我将模型实例分配为:
patient = Patient.first
physician = Physician.first
appointment = Appointment.first
appointment.patient = patient
appointment.physician = physician
在rails控制台中进行实验时,我发现使用.push()
向患者或医生添加预约可以按预期工作。
patient.appointments.push(appointment)
=> #<Appointment id: 1, physician_id: 1, patient_id: 1, appointment_date: nil, created_at: "2015-06-18 13:45:19", updated_at: "2015-06-18 13:47:30">
但是如果我使用铲子操作员附加约会physician_id
没有被保存:
patient.appointments << appointment
[#<Appointment id: 1, physician_id: nil, patient_id: 1, appointment_date: nil, created_at: "2015-06-18 13:45:19", updated_at: "2015-06-18 13:46:58">, #<Appointment id: 1, physician_id: 1, patient_id: 1, appointment_date: nil, created_at: "2015-06-18 13:45:19", updated_at: "2015-06-18 13:47:30">]
为什么它看起来是一个不同的约会实例而没有doctor_id,尽管有一个?