Q:

Associations being removed by update_attributes

I have two models which are associated through a has and belongs to many association, call them Foo and Bar. 
Now say I have a foo instance and also have bar1 and bar2. foo is already associated with bar1.
When I try to update the associations and add bar2 to foo, I run in to a problem. 
foo.update_attributes(bar_ids=>bar2.id)

This will first delete the existing association with bar1 and then add the association with bar2 so that foo.bars will only return bar2. I would like the update action to add the second association without deleting the first.
I feel like this is a simple solution but I haven't been able to find an answer. Any help would be greatly appreciated thanks!

A:

That's the behavior of the method bar_ids, to replace the elements, which is usually what is wanted. If you want to add a new element, you can either add it to the association, like this:
foo.bars << bar2

or if you need to use the method bar_ids, just first get the value and add it to the array, like this:
foo.update(bar_ids: foo.bar_ids | [bar2.id])

