繁体   English   中英

删除父项时,Rails 将子关联 ID 设置为 nil

[英]Rails Set child association id to nil when deleting parent

这是我在CollectionAlbum模型之间建立的关联:

class Collection < ActiveRecord::Base
  has_many :children, class_name: "Collection", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Collection", foreign_key: "parent_id", optional: true
  has_many :albums
end

class Album < ActiveRecord::Base
  has_many :photos, dependent: :destroy
  belongs_to :collection, optional: true
end

我刚刚删除了所有Collection的,并且我希望每个Albumcollection_id返回到NULL ,因为父级不再存在。

我如何确保在删除Album的父Collection时发生这种情况?

在您的Collection模型中使用dependent: nullify

has_many :albums, dependent: :nullify

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM