Search code examples
ruby-on-rails-4activerecordmodel-associations

Cascading multiple models


I'm deleting a Place and it's cascading the rows of PlaceUpload, but I also would like to cascade the rows of Match and TagCostumer while I am deleting a Place. How can I do that?

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

Solution

  • The solution was to use destroy and create a callback to automatically do a deep cascading.

    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