Shovel operator (<<) returning nil for instance's id in a many-to-many association

625 views Asked by At

I'm following the RailsGuides tutorial in an attempt to understand associations with join tables.

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

I assign my model instances as so:

patient     = Patient.first
physician   = Physician.first
appointment = Appointment.first

appointment.patient   = patient
appointment.physician = physician

While experimenting in the rails console I noticed that adding appointments to either patients or physicians using .push() works as expected.

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">

But if I were to use the shovel operator to append the appointment the physician_id isn't saved:

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">]

Why does it appear to be a different appointment instance with no physician_id despite there being one?

0

There are 0 answers