簡體   English   中英

通過聯接表刪除記錄

[英]Deleting a record through a join table

我確定已經回答了數百次,但是今天早上我已經搜索並嘗試了100件事,所以我只想問這個問題。 隨意將我鏈接到另一篇文章...

我有3個模型:注釋,標簽,NoteTags(加入)

筆記有很多標簽,標簽有很多筆記; 我正在嘗試銷毀Note,NoteTag鏈接被銷毀,但標簽仍保留。

楷模:

class Note < ApplicationRecord
  has_many :note_tags
  has_many :tags, -> { uniq }, through: :note_tags, dependent: :destroy
end

class Tag < ApplicationRecord
  has_many :note_tags
  has_many :notes, through: :note_tags, dependent: :destroy
end

class NoteTag < ApplicationRecord
  belongs_to :note
  belongs_to :tag
end

因此,很顯然,如果Tag仍具有其他注釋,我不希望將其刪除..但是,如果note_tag表中不再包含該注釋,則應將其刪除...

有什么辦法嗎?

謝謝

您可以在銷毀音符后銷毀孤立標簽。

def destroy
  @note = Note.find_by(id: params[:id])
  if @note
    @note.destroy_with_tags
  end
end

def destroy_with_tags
  oldtag_ids = tag_ids
  destroy
  Tag.find(oldtag_ids).each do |tag|
    tag.destroy if tag.notes == []
  end
end

如果標簽數量很多,可能還有其他更有效的方法。

第二種方法(當前不起作用)

使用普通的destroy並添加回調以銷毀孤立標記。 此選項不起作用,但可能與一些我無法測試的更改一起起作用。

class Note << ApplicationRecord
  before_destroy :old_tags
  after_destroy :destroy_orphan_tags

  def old_tags
    @oldtag_ids = tag_ids
  end

  def destroy_orphan_tags
    #Destroy tags that were associated to this note, if there are no more notes
    Tag.find(@oldtag_ids).joins(:note_tags).group('tags.id').having("count (*) = 0").destroy_all
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM