Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and removing from a has_many :through relation

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?

like image 619
dteoh Avatar asked Dec 11 '10 05:12

dteoh


1 Answers

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
like image 126
Kevin Avatar answered Sep 26 '22 01:09

Kevin