1

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?

3 Answers 3

3

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
2
  • Have you considered the performance implications of cleaning up your tags every time an article is deleted? You might want to consider a cron job running an sql script to accomplish this. Nov 16, 2009 at 18:51
  • It depends on the application. If articles are deleted only occasionally, then it may be more efficient than running the task on a set schedule! Also, since he's working in Rails, I would recommend a Rake task set to a cron job so as to keep the app consistent and packaged.
    – Ron Gejman
    Nov 16, 2009 at 19:41
2

In your remove_orphaned_tags method, what is "tags" that you do an each on?

Wouldn't you need like Tag.all ?

1
  • Thanks; I guess I had assumed tags was self.tags, which probably wouldn't have worked anyway (oh, sleep deprivation...).
    – neezer
    Nov 16, 2009 at 17:01
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.