【问题标题】:association doesn't get deleted with dependent: true关联不会被依赖删除:true
【发布时间】:2015-05-26 13:01:11
【问题描述】:

我有一个连接模型 item_photos 用于 item 和 photo 模型

class ItemPhoto < ActiveRecord::Base
    belongs_to :item
    belongs_to :photo
end

class Item < ActiveRecord::Base
    has_many :item_photos
    has_many :photos, through: :item_photos, dependent: :destroy
end


class Photo < ActiveRecord::Base
    has_many :item_photos, dependent: :destroy
    has_many :items, through: :item_photos, dependent: :destroy
end

删除照片时,如果它是最后一张(某种引用计数),或者至少能够在之前运行一些代码,我想删除它

这可能吗?

【问题讨论】:

    标签: ruby-on-rails-4 associations destroy


    【解决方案1】:

    一种方法是使用关联回调,例如after_remove。

    class Photo < ActiveRecord::Base
      has_many :item_photos, dependent: :destroy
      has_many :items, through: :item_photos, dependent: :destroy, after_remove: :do_stuff
    
      private
    
      def do_stuff
        # ...
      end
    end
    

    此处的文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html(没有直接链接,但搜索关联回调)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2013-03-24
      相关资源
      最近更新 更多