如果不存在 has_many 个实例,则删除 belongs_to 个实例

delete belongs_to instance if no instances of has_many exist

对于这些模型:

class Folder < ApplicationRecord
   has_many :documents_folders_requests, dependent::destroy 
end

class DocumentsFoldersRequest < ApplicationRecord
  belongs_to :folder
  belongs_to :child_folder, class_name: "Folder", optional: true
end

如果 DocumentsFoldersRequest 记录被删除,并且不存在使用该 Folder 记录作为 folder_idchild_folder_id 的其他 documents_folders_request 记录,有没有办法自动删除Folder记录?此时它会被认为是“孤立的”——因为它在任何关联中都找不到,并且没有 folders_controller#index 可以在任何地方显示所有文件夹记录。 这可以从模型中完成吗?

示例:

dfr = DocumentsFoldersRequest.find_by(document_id: 123)

folder_id = dfr.folder.id 
=> [1]

dfr.destroy_all
=> true

# is there a better way to write the following: 
if DocumentsFoldersRequest.where(folder: folder_id).nil? && DocumentsFoldersRequest.where(child_folder: folder_id).nil?
  folder = Folder.find(folder_id)
  folder.destroy
end 

有几个选项。主要归结为您何时要执行此操作。

我建议你在删除 DocumentsFoldersRequest

时这样做

任何时候删除一个,检查父 folderchild_folder:

class DocumentsFoldersRequest < ApplicationRecord
  after_destroy :check_for_orphaned_folder

  def check_for_orphaned_folder
    folder.destroy if folder.documents_folders_requests.none?
    child_folder.destroy if child_folder.documents_folders_requests.none?
  end

end