سؤال

مع منتظم has_many, ، هناك خيار :dependent => :destroy لحذف الجمعيات عند حذف السجل الأصلي. مع has_many :through, ، قد يكون هناك آباء آخرين يرتبطون بسجلات الطفل، لذلك :dependent => :destroy ليس لديه أي تأثير.

كيف تضمن حذف السجلات الطفولة بعد أن تتيم من آخر جمعية HMT؟

هل كانت مفيدة؟

المحلول

يبدو أن الحل الذي وجدته هو after_destroy رد الاتصال، مثل هذا:

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

نصائح أخرى

في نموذج الانضمام، استخدم "ينتمي_to: النموذج، المعال:: تدمير"

على سبيل المثال، إذا كنت ترغب في تدمير مريض بمجرد تدمير طبيبهم، والطبيب Has_many المرضى على الرغم من المواعيد

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top