2009-11-16 40 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 
相關問題