1
votes

Below code is from http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

class CreateAppointments < ActiveRecord::Migration
 def change
  create_table :physicians do |t|
   t.string :name
   t.timestamps null: false
  end

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

create_table :appointments do |t|
  t.belongs_to :physician, index: true
  t.belongs_to :patient, index: true
  t.datetime :appointment_date
  t.timestamps null: false
end

end end

In the above example how do i:

1) Create/destroy a relation between a physician and patient. Do i just use:

Create: Appointment.create(physician_id, patient_id)
Destroy: (i have no clue hot to do this)

What is the correct way to do it?

2) How would i access all the appointment_date in the Appointment model for a particular patient or physician?

2
I am currently creating the relationships using create. As for the destroy i have been destroying the record on the console. (I am very new to rails sorry if this is really basic)fox
I just found the following on another question to create a relationship:@course.topics << Topic.new(params[:topic])fox
Your code snippet only assigns a new Topic to a temporary varaible named @course. So although the topic is now part of @course, and accessible through @course.topics, there's no persistent relationship.bo-oz

2 Answers

1
votes

You can create an appointment from either the physician or the patient, depending on your preference:

@patient = Patient.find(params[:id])
@patient.appointments.create(physician: *object*, appointment_date: *datetime object*)  # auto sets the patient to match the @patient.id

#or from the physician
@physician = Physician.last #select the last physician
@physician.appointments.create(patient: *object*, appointment_date: *datetime object*) # auto sets the physician to match the @physician.id

If you have both ID's, you can also create it this way:

Appointment.new(patient: *Patient object*, physician: *Physician object*, appointment_date: *datetime object*)

To destroy a record, just find the active record object and call destroy on it. Play around in console to see how it works. For instance:

Patient.find(id).appointments.last.destroy #destroys the last appointment for a patient with id

or find and delete an Appointment directly:

# find active record and then call destroy
@appointment = Appointment.find(1) # find appointment with ID: 1
@appointment.destroy

#call destroy directly by chaining commands
Appointment.find(1).destroy #does the exact same thing as above.
0
votes

1/

 Appointment.find_by(physician: @physician, patient: @patient).destroy

2/

 @patient.appointments.pluck(:appointment_date)