ruby-on-rails - 映射关联不执行 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
我能做些什么来完成这项工作?
解决方案
推荐阅读
- python - numpy_financial irr 函数返回“ValueError:输入必须是 rank-1 数组”
- matplotlib - 如何将多个变量添加到 matplotlib 标题
- php - 需要关于 PHP 中数组操作的有效解决方案的建议
- azure-devops - 在 Azure DevOps Server 2019(本地)中,将构建变量从构建流向相应版本的自然方式是什么?
- api - Mailgun 邮件列表“发件人”标头
- android - 在我的 Android 应用程序中检测 5G NR (SA/NSA)
- python - tabula_py 问题 如何提取分布在多个页面中的 pdf 表格数据
- python - 无效的文件路径或缓冲区对象类型:
- c# - 如何自动调整网格中内容的大小以使其适合所有分辨率
- excel - 仅键盘格式刷非相邻单元格 Excel