0

http://guides.rubyonrails.org/association_basics.html

Based on the above example, I created:

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

Can someone guide me how can I perform a cascading delete action.

  1. if I delete a Patient, I want all appointments for the patient deleted. Do I need to use dependent keyword somewhere ? Can someone demonstrate how to solve this.

  2. How do I delete all appointments for a particular patient ?

Thanks in advance!

Axil
  • 3,606
  • 10
  • 62
  • 136
  • possible duplicate of [Cascade delete in Ruby ActiveRecord models?](http://stackoverflow.com/questions/1896777/cascade-delete-in-ruby-activerecord-models) – Wand Maker Aug 09 '15 at 17:15

1 Answers1

1
class Patient < ActiveRecord::Base
  has_many :appointments, dependent: :destroy
  has_many :physicians, through: :appointments
end

Patient.find(id).destroy

This should work for you. Make sure you use destroy and not delete because if you use delete you won't have the cascading effect you expect.

Update 2:

If you want to destroy all appointments but not the patient you can do this:

Patient.find(id).appointments.destroy_all

Marius Pop
  • 1,431
  • 2
  • 19
  • 32
  • can you also provide the answer for: How do I delete all appointments for a particular patient ? (just the appointments, not the patient) Thanks – Axil Aug 09 '15 at 17:39