# HABTM insertion deletes old entries

**URL:** <https://www.ruby-forum.com/t/habtm-insertion-deletes-old-entries/158998>\
**Category:** Ruby\
**Created:** [January 30, 2009, 6:58am UTC](https://www.ruby-forum.com/t/habtm-insertion-deletes-old-entries/158998 "2009-01-30T06:58:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![preethi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f04885/32.png) [@preethi](https://www.ruby-forum.com/u/preethi)\
**Post date:** [January 30, 2009, 6:58am UTC](https://www.ruby-forum.com/t/habtm-insertion-deletes-old-entries/158998/1 "2009-01-30T06:58:26Z")

</div>

Hi,

I’ve 2 models Profile & User and they have HABTM relationship.

* * *

## class Vcprofile \< ActiveRecord::Base has\_and\_belongs\_to\_many :users end

## class Vcgbluser \< ActiveRecord::Base has\_and\_belongs\_to\_many :vcprofiles end

I’ve a screen designed in which i can assign one profile to so many  
users(through list box).

## Initially if i assign 2 users(say sam and rose) to the profile(say profile1), an entry is made into the “profiles\_users” mapping table.

## @profile.users = @User (@user is a list of users selected)

But later when i open the same page and select two more users(say jack  
and jil) for the same profile(profile1) and submit, the old two  
entries(sam and rose) are delted from the mapping table(profiles\_uses)  
and these two entries are added.

Why does HABTM delete the old entries(sam and rose) when a new  
assignment is made?

Can anyone help?

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![preethi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f04885/32.png) [@preethi](https://www.ruby-forum.com/u/preethi)\
**Post date:** [January 30, 2009, 2:08pm UTC](https://www.ruby-forum.com/t/habtm-insertion-deletes-old-entries/158998/2 "2009-01-30T14:08:54Z")

</div>

In a HABTM relationship, assigning a new collection (using =) will  
delete  
the old collection and set it to the new collection. If you want to add  
to a  
collection, use the \<\< operator.

---

<div class="post-metadata">

**Author:** ![preethi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f04885/32.png) [@preethi](https://www.ruby-forum.com/u/preethi)\
**Post date:** [January 30, 2009, 2:24pm UTC](https://www.ruby-forum.com/t/habtm-insertion-deletes-old-entries/158998/3 "2009-01-30T14:24:33Z")

</div>

Scott Lillibridge wrote:

> In a HABTM relationship, assigning a new collection (using =) will  
> delete  
> the old collection and set it to the new collection. If you want to add  
> to a  
> collection, use the \<\< operator.

It is working now.  
Thank you so much Scott 🙂
