这是我在Collection
和Album
模型之间建立的关联:
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
,我希望每个Album
的collection_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