Mongo Mapper Won't Destroy Document During Loop

50 Views Asked by At

This must be a simple answer, but I'm puzzled. I'm running a Sinatra app with Mongo Mapper, and trying to destroy a handful of documents associated with the user ids in the rem_users array. The following loop looks up the associated GroupMember for each element of rem_users, and tries to delete it. When I run it, the GroupMember is not destroyed.

rem_users.each do |du_id|
  ###
  GroupMember.first('$and' => [{dealer_user_id: du_id}, {group_id: g.id}] ).destroy
end

rem_users is an array of BSON ids that have been converted to strings. I have verified that the query is pulling up the correct GroupMember with this query, and if I put a binding.pry where the ### is in the example and copy-paste the exact next line of the loop, the GroupMember is successfully destroyed. I have tried:

remgm = GroupMember.all('$and' => [{group_id: g.id}, {dealer_user_id: rem_users}])
remgm.each {|gm| GroupMember.destroy(gm.id)}

and the result is the same. There are no validations of any kind on the GroupMember model. Thanks!

1

There are 1 best solutions below

1
Fog Labs On

Figured it out:

So the Group was loaded at the top of the block:

g = Group.find(params[:group_id])
redirect '/' unless g

...

rem_users.each do |du_id|
  ###
  GroupMember.first('$and' => [{dealer_user_id: du_id}, {group_id: g.id}]   ).destroy
end

g.save 

And then saved after the destroying had happened. So it seems that when g was loaded, it loaded g.members along with it. The loop was doing everything correctly, but upon saving the already-loaded Group, I re-saved all the destroyed GroupMembers.

All I had to do was save the Group before removing users, and the destroying worked as expected.