1

Ryan Batesの仮想属性に関する優れたチュートリアルを考えると、記事が破棄された後、そのタグが使用されなくなった場合、(タグ付けではなく)タグを破棄するにはどうすればよいですか?

私はこのようなことをしてみました:

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 に答える