通过 rails 中的多对多关系销毁实体

Destroying entities through many to many relationship in rails

我有 3 个模型。 故事、标签和标签。

一个故事通过标签有很多标签。这是我的模型:

**Story.rb**
class Story < ApplicationRecor
  has_many :taggings, dependent: :delete_all
  has_many :tags, through: :taggings
end

**Tagging.rb**
class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :story
end

**Tag.rb**
class Tag < ApplicationRecord
  has_many :taggings
  has_many :stories, through: :taggings
end

因此,当我删除故事时,我依赖于::delete_all 标签,它对与故事关联的所有标签调用单个 SQL delete 语句。如果不再有任何关联的标签,我还想删除所有标签。例如,一个故事有 1 个标签和一个通过标签的标签。当我删除那个故事时,那个故事和标签都被删除了,但那个标签仍然存在。我也希望删除该标签,因为不再有与该标签关联的标签。

我试过这个:

**Story.rb**
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings

还有这个:

**Story.rb**
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings, dependent: :destroy

两者都不起作用..关于如何处理这个问题有什么建议吗?

您可以使用 after_destroy

检查标签
class Tagging < ApplicationRecord

  after_destroy :destroy_unused_tag

  private

  def destroy_unused_tag
    tag.destroy if tag.taggings.empty?
  end

end

您的 Tagging 模型可能缺少 dependant 标签选项。

**Story.rb**
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings

**Tagging.rb**
belongs_to :story
belongs_to :tags, dependent: :destroy