代码之家  ›  专栏  ›  技术社区  ›  Andrew Vit

在删除最后一个“有多个:通过”记录后销毁关联

  •  9
  • Andrew Vit  · 技术社区  · 17 年前

    有固定的 has_many ,这是一个选择 :dependent => :destroy 删除父记录时删除关联。具有 has_many :through :依赖=>:摧毁

    如何确保在从上一个HMT关联中孤立子记录后将其删除?

    2 回复  |  直到 17 年前
        1
  •  13
  •   Andrew Vit    17 年前

    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
    
        2
  •  1
  •   suga_shane    14 年前

    在连接模型上,使用“属于:模型,依赖::销毁”

    例如,如果你想在一个病人的医生被毁灭后毁灭他,而医生已经安排了很多病人

    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