0
votes

Physician has_many Patients through Appointments
Patient has_many Physicians through Appointments

How can I make the Appointment name a concatenation of Physician name and Patient name automatically in the Appointment model?

Physician.name = 'Joe Doctor'  
Patient.name = ' Sally Smith'  
Appointment.name = "#{Patient.name} with #{Physician.name}"  

This is not our real world use but a simplified example. Thanks.

2

2 Answers

2
votes

One way of doing it would be :

class Appointment
  belongs_to :doctor
  belongs_to :patient

  before_create :set_default_name #optional it can be called imperatively

  def set_default_name
    if patient && doctor
      self.name= "#{patient.name} with #{doctor.name}"
    end
  end
end

That way whenever you add a patient to a doctor.patients it should set the appointment's name automatically:

@doctor.patients << @patient
@doctor.appointments.last.name # => "Dr Who with Mr Spock" 
1
votes

Assume you have one patient and one physician in each appointment, you can define a method in your Appointment model like:

def name
  self.patient.name + ' with ' + self.physician.name
end