문제

규칙적으로 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