1

鉴于Ryan Bates 关于 Virtual Attributes 的精彩教程,如果文章被销毁后不再使用该标签,我将如何销毁标签(而不是标签)?

我试着做这样的事情:

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

...但这似乎不起作用(删除文章后标签仍然存在,即使没有其他文章使用它们)。我应该怎么做才能做到这一点?

4

3 回答 3

3

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
于 2009-11-16T16:51:12.363 回答
2

在你的remove_orphaned_tags方法中,你做的“标签”是什么each

你不需要喜欢Tag.all吗?

于 2009-11-16T16:45:40.817 回答
0

我知道为时已晚,但对于遇到同样问题的人来说,这是我的解决方案:

 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
于 2013-11-09T22:00:13.633 回答