给予 瑞恩*贝茨是伟大的教程上的虚拟性, ,我怎么会去毁坏一个标记(不加标签)如,一旦制品被破坏,该标记不再使用?

我试图做这样的事情:

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

...但是,这不起作用(标记仍然存在之后的条文被删除,即使没有任何其他文使用)。什么我应该做的为了完成这个吗?

有帮助吗?

解决方案

在你 remove_orphaned_tags 方法,什么是"标签",你做一个 each 上?

你不需要喜欢 Tag.all ?

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top