Domanda

Con un has_many regolare, c'è la possibilità di :dependent => :destroy per eliminare le associazioni quando il record padre viene eliminato. Con has_many :through, ci potrebbero essere altri genitori associati ai record figlio, in modo da :dependent => :destroy non ha alcun effetto.

Come si fa a garantire record figlio vengono cancellati dopo che sono orfani dall'ultimo associazione HMT?

È stato utile?

Soluzione

La soluzione che ho trovato sembra essere un callback after_destroy, come questa:

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

Altri suggerimenti

Nel modello aderire, utilizzare "belongs_to: il modello, in funzione:: distruggere"

Per esempio, se si vuole distruggere un paziente una volta che il loro medico è distrutto, ed i pazienti medico has_many però gli appuntamenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top