【问题标题】:Cascading multiple models级联多个模型
【发布时间】:2016-02-03 01:38:05
【问题描述】:

我正在删除一个地方,它正在级联 PlaceUpload 的行,但我也想在删除地方时级联 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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2015-04-10
      • 2023-03-10
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      相关资源
      最近更新 更多