문제

주어진 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

... 그러나 그것은 작동하지 않는 것 같습니다 (다른 기사가 사용하지 않더라도 기사가 삭제 된 후에도 태그가 여전히 존재합니다). 이것을 달성하기 위해 무엇을해야합니까?

도움이 되었습니까?

해결책

당신의 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