RoR: Destroy association with has_many, :through if orphaned
-
20-09-2019 - |
Question
Given Ryan Bates's great tutorial on Virtual Attributes, how would I go about destroying a Tag (not Tagging) if, once the article is destroyed, that Tag is no longer used?
I tried doing something like this:
class Article < ActiveRecord::Base
...
after_destroy :remove_orphaned_tags
private
def remove_orphaned_tags
tags.each do |tag|
tag.destroy if tag.articles.empty?
end
end
end
... but that doesn't seem to work (the tags still exist after the article is deleted, even though no other article uses them). What should I be doing to accomplish this?
Solution
In your remove_orphaned_tags
method, what is "tags" that you do an each
on?
Wouldn't you need like Tag.all
?
OTHER TIPS
JRL is correct. Here is the proper code.
class Article < ActiveRecord::Base
...
after_destroy :remove_orphaned_tags
private
def remove_orphaned_tags
Tag.find(:all).each do |tag|
tag.destroy if tag.articles.empty?
end
end
end
i know it's way too late, but for people who encounter the same issue, this is my solution:
class Article < ActiveRecord::Base
...
around_destroy :remove_orphaned_tags
private
def remove_orphaned_tags
ActiveRecord::Base.transaction do
tags = self.tags # get the tags
yield # destroy the article
tags.each do |tag| # destroy orphan tags
tag.destroy if tag.articles.empty?
end
end
end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow