2009-11-16 75 views
1

鉴于Ryan Bates's great tutorial on Virtual Attributes,如果一旦文章被销毁,标签不再被使用,我将如何去销毁标签(而不是标签)?RoR:破坏与has_many,:通过孤立的关联

我试图做这样的事情:

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 

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

回答

2

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

你不需要像Tag.all

+0

谢谢;我想我假设'标签'是'self.tags',这可能不会起作用(哦,睡眠剥夺......)。 – neezer 2009-11-16 17:01:20

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 
+0

您是否考虑过每次删除文章时清理标签的性能影响? 您可能想要考虑运行sql脚本来完成此任务的cron作业。 – 2009-11-16 18:51:04

+0

这取决于应用程序。如果文章只是偶尔被删除,那么它可能比在设定的时间表上运行任务更有效率! 另外,由于他在Rails中工作,我会推荐将一个Rake任务设置为cron作业,以保持应用程序的一致性和打包。 – 2009-11-16 19:41:02

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