Nigel
Nigel

Reputation: 1027

Destroying entities through many to many relationship in rails

I have 3 models. Story, Tag and Tagging.

A Story has many tags through taggings. Here are my models:

**Story.rb**
class Story < ApplicationRecor
  has_many :taggings, dependent: :delete_all
  has_many :tags, through: :taggings
end

**Tagging.rb**
class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :story
end

**Tag.rb**
class Tag < ApplicationRecord
  has_many :taggings
  has_many :stories, through: :taggings
end

So when I delete a story, I have dependent: :delete_all on taggings which calls a single SQL delete statement on all taggings associated with a Story. I'd like to also delete all Tags if there are no longer any taggings associated to it. For example, a story has 1 tagging and one tag through the tagging. When I delete that story, that story and tagging are deleted but that tag still remains. I'd like that tag to be removed as well since there are no taggings associated to that tag anymore.

I've tried this:

**Story.rb**
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings

and this:

**Story.rb**
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings, dependent: :destroy

Both doesnt work.. Any advice on how to handle this?

Upvotes: 0

Views: 32

Answers (2)

Jokūbas
Jokūbas

Reputation: 331

Your Tagging model might be missing dependant option for tags.

**Story.rb**
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings

**Tagging.rb**
belongs_to :story
belongs_to :tags, dependent: :destroy

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

You can check the tags using an after_destroy

class Tagging < ApplicationRecord

  after_destroy :destroy_unused_tag

  private

  def destroy_unused_tag
    tag.destroy if tag.taggings.empty?
  end

end

Upvotes: 1

Related Questions