# Habtm relation and dependent =\> :destroy

**URL:** <https://www.ruby-forum.com/t/habtm-relation-and-dependent-destroy/158593>\
**Category:** Rails\
**Created:** [January 25, 2009, 5:24pm UTC](https://www.ruby-forum.com/t/habtm-relation-and-dependent-destroy/158593 "2009-01-25T17:24:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pandabeer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ecd19e/32.png) [@pandabeer](https://www.ruby-forum.com/u/pandabeer)\
**Post date:** [January 25, 2009, 5:24pm UTC](https://www.ruby-forum.com/t/habtm-relation-and-dependent-destroy/158593/1 "2009-01-25T17:24:21Z")

</div>

Hi all ,  
I have a habtm relation between 2 tables:

- users
- rights

If there a way to affect a destroy dependance on those 2 tables only for  
the last instance? In my opinion, dependent =\> :destroy is not the  
solution because this delete all the linked instance.

For example, if I have:

# in User model this:

- “Joooooo”
- “Jeannnn”
- “Tommmm”

# in Right model this:

- “Write”
- “Read”

# in the habtm relation this:

- “Joooooo” can “Write”
- “Joooooo” can “Read”
- “Jeannnn” can “Read”

I would like to be able to delete “Read” in Right model, and automaticly  
deleting “Jeannnn” user too, because this user have no other right. But  
without deleting “Joooooo” user (because he remains have a right named  
“Write”).

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![pandabeer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ecd19e/32.png) [@pandabeer](https://www.ruby-forum.com/u/pandabeer)\
**Post date:** [January 26, 2009, 5:01pm UTC](https://www.ruby-forum.com/t/habtm-relation-and-dependent-destroy/158593/2 "2009-01-26T17:01:46Z")

</div>

Panda B. wrote:

> For example, if I have:
> 
> - “Jeannnn” can “Read”
> 
> I would like to be able to delete “Read” in Right model, and automaticly  
> deleting “Jeannnn” user too, because this user have no other right. But  
> without deleting “Joooooo” user (because he remains have a right named  
> “Write”).

Perhaps something like:

class Right  
after\_destroy do  
User.find(:all, :uniq =\> true, :joins =\> :rights,  
:conditions =\> ‘rights.id is NULL’).each(&:destroy)  
end  
end

–  
Rails Wheels - Find Plugins, List & Sell Plugins -  
[http://railswheels.com](http://railswheels.com)
