# Acts\_as\_taggable gem: deleting tags

**URL:** <https://www.ruby-forum.com/t/acts-as-taggable-gem-deleting-tags/94250>\
**Category:** Rails\
**Created:** [April 26, 2006, 7:31pm UTC](https://www.ruby-forum.com/t/acts-as-taggable-gem-deleting-tags/94250 "2006-04-26T19:31:00Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [April 26, 2006, 7:31pm UTC](https://www.ruby-forum.com/t/acts-as-taggable-gem-deleting-tags/94250/1 "2006-04-26T19:31:00Z")

</div>

I have the following quick-and-dirty hack in my model:

def after\_destroy  
# search for orphaned tags and delete them  
orphans = Resource.tags\_count :count =\> ‘= 0’  
orphans.keys.each {|tag| Tags.find\_by\_name(‘tag’).destroy}  
end

It’s nice from a readable code perspective, but it seems inefficient -  
is there some way to do this with only one query?

martin

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [April 26, 2006, 8:33pm UTC](https://www.ruby-forum.com/t/acts-as-taggable-gem-deleting-tags/94250/2 "2006-04-26T20:33:25Z")

</div>

Nevermind, this doesn’t even work - it was masked by another problem  
in my code! So how would I go about deleting orphanned tags?

martin

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [April 26, 2006, 9:13pm UTC](https://www.ruby-forum.com/t/acts-as-taggable-gem-deleting-tags/94250/3 "2006-04-26T21:13:57Z")

</div>

Martin  
\>So how would I go about deleting orphanned tags?

I added this method to Tag to find orphan tags:

def Tag.find\_orphans  
Tag.find\_by\_sql(‘select tags.\* from tags left JOIN taggings ON  
tags.id = taggings.tag\_id where taggings.tag\_id is null’)  
end

Alain

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [April 26, 2006, 9:23pm UTC](https://www.ruby-forum.com/t/acts-as-taggable-gem-deleting-tags/94250/4 "2006-04-26T21:23:29Z")

</div>

On 4/27/06, Alain R. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Martin  
> \>So how would I go about deleting orphanned tags?
> 
> I added this method to Tag to find orphan tags:
> 
> def Tag.find\_orphans  
> Tag.find\_by\_sql(‘select tags.\* from tags left JOIN taggings ON  
> tags.id = taggings.tag\_id where taggings.tag\_id is null’)  
> end

Thanks! Looks like I need to go back and relearn SQL properly.

martin
