views:

183

answers:

2

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?

+2  A: 

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

Wouldn't you need like Tag.all ?

JRL
Thanks; I guess I had assumed `tags` was `self.tags`, which probably wouldn't have worked anyway (oh, sleep deprivation...).
neezer
+3  A: 

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
Ron Gejman
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.
Jeff Paquette
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