轨道 删除父项时将子关联 ID 设置为 nil



这是我在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

https://guides.rubyonrails.org/association_basics.html#options-for-has-many

您需要nullify关联foreign_key

最新更新