ROR: تدمير بالتعاون مع has_many،: من خلال إذا الأيتام
-
20-09-2019 - |
سؤال
ونظرا تعليمي ريان بيتس كبير على سمات الظاهري ، كيف يمكن أن أذهب عن تدمير الوسم (ليس توصيف) إذا، مرة واحدة يتم تدمير هذه المادة، لم يعد يستخدم هذا الوسم؟
وحاولت القيام بشيء من هذا القبيل:
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
لا تنتمي إلى StackOverflow