他のヒント

JRLは正しいです。ここで適切なコードです。

 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

私はそれがあまりにも遅知っているが、同じ問題に遭遇した人々のために、 これは私のソリューションです:

 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
scroll top