【问题标题】:Rails Set child association id to nil when deleting parentRails在删除父项时将子关联ID设置为nil
【发布时间】:2019-12-01 14:50:41
【问题描述】:

这是我在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 时发生这种情况?

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

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

    has_many :albums, dependent: :nullify
    

    【讨论】:

    • 谢谢!就是这样。
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多