Détruire les associations après la dernière has_many: par enregistrement est supprimé
-
12-09-2019 - |
Question
Avec une has_many
régulière, il y a la possibilité de :dependent => :destroy
supprimer les associations lorsque l'enregistrement parent est supprimé. Avec has_many :through
, il pourrait y avoir d'autres parents associés aux dossiers de l'enfant, donc :dependent => :destroy
n'a pas d'effet.
Comment vous assurez-vous des enregistrements enfants sont supprimés après avoir été rendus orphelins de la dernière association HMT?
La solution
La solution que j'ai trouvé semble être un rappel after_destroy
, comme ceci:
class Parent < ActiveRecord::Base
has_many :children, :through => :parentage
after_destroy :destroy_orphaned_children
private
def destroy_orphaned_children
children.each do |child|
child.destroy if child.parents.empty?
end
end
end
Autres conseils
Sur le joint modèle, utilisez "belongs_to: modèle, en fonction:: détruire"
par exemple, si vous voulez détruire un patient une fois que leur médecin est détruit, et les patients has_many médecin quoique rendez-vous
Class Appointment
belongs_to :doctor
belongs_to :patient, dependent: :destroy
Class Doctor
has_many :appointments, dependent: :destroy
has_many :patients, through: :appointments
Class Patient
has_many :appointments
has_many :doctors, through: :appointments