简体   繁体   English

通过联接表删除记录

[英]Deleting a record through a join table

I'm sure this has been answered hundreds of times, but I have searched and tried 100 things this morning so I am just going to ask the question. 我确定已经回答了数百次,但是今天早上我已经搜索并尝试了100件事,所以我只想问这个问题。 Feel free to just link me to another post... 随意将我链接到另一篇文章...

I have 3 models: Notes, Tags, NoteTags (join) 我有3个模型:注释,标签,NoteTags(加入)

Notes have many tags, tags have many notes; 笔记有很多标签,标签有很多笔记; I'm trying to destroy a Note, the NoteTag link is being destroyed but the Tags remain. 我正在尝试销毁Note,NoteTag链接被销毁,但标签仍保留。

Models: 楷模:

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

So, obviously if the Tag still has a different note that has it, I don't want it to be deleted.. but if it's no longer featured in the note_tag table, it should be removed... 因此,很显然,如果Tag仍具有其他注释,我不希望将其删除..但是,如果note_tag表中不再包含该注释,则应将其删除...

Is there any way of doing this?! 有什么办法吗?

Thanks 谢谢

You could destroy orphan tags after destroying the note. 您可以在销毁音符后销毁孤立标签。

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

There may be other more efficient approach, in case the number of tags is big. 如果标签数量很多,可能还有其他更有效的方法。

Second approach (currently not working) 第二种方法(当前不起作用)

Use the normal destroy and add a callback to destroy orphan tags. 使用普通的destroy并添加回调以销毁孤立标记。 This option does not work, but might work with some changes I could not test. 此选项不起作用,但可能与一些我无法测试的更改一起起作用。

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