【问题标题】:Destroying entities through many to many relationship in rails通过rails中的多对多关系销毁实体
【发布时间】:2020-09-13 14:54:52
【问题描述】:

我有 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 删除语句。如果不再有任何关联的标签,我还想删除所有标签。例如,一个故事有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

两者都不起作用..有关如何处理此问题的任何建议?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    您可以使用after_destroy检查标签

    class Tagging < ApplicationRecord
    
      after_destroy :destroy_unused_tag
    
      private
    
      def destroy_unused_tag
        tag.destroy if tag.taggings.empty?
      end
    
    end
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-25
        • 1970-01-01
        • 2013-04-25
        • 2016-04-24
        相关资源
        最近更新 更多