首页 > 解决方案 > 映射关联不执行 after_destroy

问题描述

如果我通过设置集合来更改模型的关联,则 after_destroy 和 after_remove 回调都不会触发。

if image_params[:tags]
    @image.tags = image_params[:tags].map { |tag|
    Tag.create(title: tag) unless Tag.where(title: tag).exists?
    Tag.find_by(title: tag)
  }
end

class TagRelation < ApplicationRecord
  belongs_to :tag
  belongs_to :taggable, polymorphic: true

  # Destroy tag if no other items are related
  after_destroy do
    self.tag.check_count
  end
end

class Tag < ApplicationRecord
  has_many :tag_relations, dependent: :destroy, after_remove: :check_count
  has_many :gallery_images, through: :tag_relations, source_type: 'GalleryImage', source: :taggable
  has_many :streams, through: :tag_relations, source_type: 'Stream', source: :taggable

  validates :title, uniqueness: true

  def count
    self.tag_relations.count
  end

  def check_count
    self.destroy if self.count === 0
  end
end

我能做些什么来完成这项工作?

标签: ruby-on-railsruby

解决方案


推荐阅读