RoR: Distruggi associazione con has_many,: attraverso se orfani
-
20-09-2019 - |
Domanda
grande esercitazione di Ryan Bates su attributi virtuali , come sarebbe vado di distruggere un tag (non Tagging) se, una volta che l'articolo è distrutto, quel tag non è più utilizzato?
Ho provato a fare qualcosa di simile:
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
... ma questo non sembra funzionare (esistono ancora i tag dopo l'articolo viene cancellato, anche se nessun altro articolo li usa). Cosa dovrei fare per raggiungere questo obiettivo?
Soluzione
Nel tuo metodo remove_orphaned_tags
, ciò che è "tag" che si fa un each
su?
Non ti bisogno di come Tag.all
?
Altri suggerimenti
JRL è corretta. Ecco il codice corretto.
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
Lo so che è troppo tardi, ma per le persone che incontrano lo stesso problema, questa è la mia soluzione:
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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow