5

From the Rails associations guide, they demonstrate a many-to-many relationship using has_many :through like so:

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

How would I create and remove appointments?

If I've got a @physician, do I write something like the following for creating an appointment?

@patient = @physician.patients.new params[:patient]
@physician.patients << @patient
@patient.save # Is this line needed?

What about code for deleting or destroying? Also, if a Patient no longer existed in the Appointment table will it get destroyed?

1 Answer 1

7

In your code of creating an appointment, the second line is not needed, and using #build method instead of #new:

@patient = @physician.patients.build params[:patient]
@patient.save  # yes, it worked

For destroying an appointment record you could simply find it out and destroy:

@appo = @physician.appointments.find(1)
@appo.destroy

If you want to destroy the appointment records along with destroying a patient, you need to add the :dependency setting to has_many:

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments, :dependency => :destroy
end
3
  • 1
    Thanks, I assume that deleting the appointment will also remove the physician from the patient and vice versa?
    – dteoh
    Dec 11, 2010 at 7:17
  • 1
    No, it won't unless you add :dependency => :destroy to belongs_to.
    – Kevin
    Dec 11, 2010 at 7:25
  • Actually the :dependency setting simply add a before_destroy hook to the model. Without this no other model would be affected when destroying a model record.
    – Kevin
    Dec 11, 2010 at 7:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.