Maayan Naveh
Maayan Naveh

Reputation: 370

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

I have three models. A collection has many searches through items. When a collection is destroyed, I'd like its items to be destroyed, but searches to be nullified, since they are still valid objects on their own. Can this be done?

Here are my models:

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

Upvotes: 1

Views: 1167

Answers (1)

davegson
davegson

Reputation: 8331

You can just delete the items, just add dependent: :destroy to has_many :items.

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

After destroying a collection, the item is destroyed but the search will remain.

second solution

You could even apply dependent: :nullify to has_many :searches - getting the same result.

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

From 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.

Upvotes: 1

Related Questions