依赖::仅破坏到二级,有很多通过关联

Dependent: :destroy only to the 2nd degree in has many through association

我有三个模型。一个 collection 有很多 searchesitems。 当 collection 被销毁时,我希望它的 items 被销毁,但 searches 被取消,因为它们本身仍然是有效的对象。 这能做到吗?

这是我的模型:

class Collection < ApplicationRecord
  has_many :searches, through: :items
  has_many :items
  has_many :searches, through: :suggestions
  has_many :suggestions
end

class Item < ApplicationRecord
  belongs_to :collection
  belongs_to :search
end

class Search < ApplicationRecord
  has_many :collections, through: :items
  has_many :items
  has_many :collections, through: :suggestions
  has_many :suggestions
end

可以删除项目,只需将dependent: :destroy添加到has_many :items

class Collection < ApplicationRecord
  has_many :searches, through: :items
  has_many :items, dependent: :destroy
end

销毁 collection 后,该物品将被销毁,但搜索将保留。

第二种解法

您甚至可以将 dependent: :nullify 应用于 has_many :searches - 得到相同的结果。

class Collection < ApplicationRecord
  has_many :searches, through: :items, dependent: :nullify
  has_many :items
end

来自 the docs:

collection.delete(object, …)

Removes one or more objects from the collection by setting their foreign keys to NULL. Objects will be in addition destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent: :delete_all.

If the :through option is used, then the join records are deleted (rather than nullified) by default, but you can specify dependent: :destroy or dependent: :nullify to override this.