[英]Rails Set child association id to nil when deleting parent
这是我在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.