Reputation: 57
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?
Upvotes: 1
Views: 312
Reputation: 2872
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.
Upvotes: 1
Reputation:
1/
Appointment.find_by(physician: @physician, patient: @patient).destroy
2/
@patient.appointments.pluck(:appointment_date)
Upvotes: 0