级联多个模型

Cascading multiple models

我正在删除一个 Place,它正在级联 PlaceUpload 的行,但我还想在删除 Place 的同时级联 Match 和 TagCostumer 的行。我怎样才能做到这一点?

class Place < ActiveRecord::Base
    has_many :place_uploads
end

class PlaceUpload < ActiveRecord::Base
    belongs_to :place
    has_many :matches
    has_many :tags_customers
end

class TagsCustomer < ActiveRecord::Base
    belongs_to :place_upload
    belongs_to :tag
end

class Match < ActiveRecord::Base
    belongs_to :place_upload
    belongs_to :customer
end

解决方案是使用 destroy 并创建一个回调来自动进行深度级联。

class Place < ActiveRecord::Base

    before_destroy :delete_children_objects

    has_many :place_uploads, :dependent => :destroy

    protected

        def delete_children_objects
            @places = PlaceUpload.where(place_id: id)
            @places.each do |place|
                TagsCustomer.where(place_upload_id: place.id).destroy_all
                Match.where(place_upload_id: place.id).destroy_all
            end
        end
end