jnunemaker/mongomapper — Issue #334: Removing object from a many array doesn't work
Author: poitch
Created: 2011-10-27 23:47:54+00:00
State: open

It makes sense in a way since when declaring *many* relationship you also declare an associated array of ids, but if you remove an element from the many attribute itself and save, then nothing happens. Obviously removing from the corresponding ids array work but it is just a bit un-natural that way.

```ruby
require 'test/unit'
require 'mongo_mapper'

class User
include MongoMapper::Document
key :name
end

class Group
include MongoMapper::Document
key :name

key :member_ids, Array
many :members, :class_name => 'User', :in => :member_ids
end

class ManyToManyTest < Test::Unit::TestCase
def setup
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = 'many_to_many_test'
MongoMapper.connection.drop_database('many_to_many_test')

userA = User.create(:name => "UserA")
userB = User.create(:name => "UserB")

groupA = Group.new(:name => "GroupA")
groupA.members << userA
groupA.members << userB
groupA.save
end

def test_delete
userB = User.find_by_name("UserB")
groupA = Group.find_by_name("GroupA")

assert_equal 2, groupA.members.size

groupA.members.delete(userB)
groupA.save

# In memory was obviously well handled
assert_equal 1, groupA.members.size

# Now going to mongo
groupA.reload
assert_equal 1, groupA.members.size

groupA = Group.find_by_name("GroupA")
assert_equal 1, groupA.members.size

end

def test_delete_by_id
userB = User.find_by_name("UserB")
groupA = Group.find_by_name("GroupA")

assert_equal 2, groupA.members.size

groupA.member_ids.delete(userB.id)
groupA.save

# In memory obviously that does not match anymore without a reload...
assert_equal 1, groupA.members.size

# Now going to mongo
groupA.reload
assert_equal 1, groupA.members.size

end
end
```