级联多个模型

时间:2016-02-03 01:38:06

标签: ruby-on-rails-4 activerecord model-associations

我删除了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

1 个答案:

答案 0 :(得分:0)

解决方案是使用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