Sven Kirsten
Sven Kirsten

Reputation: 518

RAILS 6 - How to update a HAS_MANY THROUGH table?

Lets say I habe this pupolar basic example:

enter image description here

With the migrations:

class CreateAppointments < ActiveRecord::Migration[5.0]
  def change
    create_table :physicians do |t|
      t.string :name
      t.timestamps
     end

  create_table :patients do |t|
    t.string :name
    t.timestamps
  end

  create_table :appointments do |t|
    t.belongs_to :physician
    t.belongs_to :patient
    t.datetime :appointment_date
    t.timestamps
  end
end
end

My only question is here, what would the command to create a new relation between physican and patient but do also update the appointment_date field in the "appointments" table ?

enter image description here

Upvotes: 0

Views: 489

Answers (2)

Rafayet Monon
Rafayet Monon

Reputation: 1179

You can do it easily like below. I guess you already have physician and patient in database -

@physycian  = Physician.last
@patient    = Patient.last
@physycian.appointments.create(patient_id: @patient.id, appointment_date: Time.current )

Also can be done using patient

@patient.appointments.create(physycian_id: @physycian.id, appointment_date: Time.current )

Upvotes: 1

Amit Patel
Amit Patel

Reputation: 15985

There are multiple ways.

1) Via Physician instance

Assuming you have physician and patient instance

physician.appointments.create(patient: patient, appointment_date: <INSERT DATE HERE>)

2) Via Patient instance

same as 1 but the association flips

Assuming you have physician and patient instance

patient.appointments.create(physician: physician, appointment_date: <INSERT DATE HERE>)

3) Using Appointment model

same as 1 but the association flips

Assuming you have physician and patient instance

Appointment.create(physician: physician, patient: patient, appointment_date: <INSERT DATE HERE>)

Upvotes: 2

Related Questions