-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
-
None
The current implementation of references_and_referenced_in_many#nullify method is causing crazy memory bloats if you have a few hundred referenced records you want to nullify.
current code:
def nullify load! and target.each do |doc| base.send(metadata.foreign_key).delete(doc.id) dereference(doc) end target.clear end
This could be extremely painful if you have hundreds or thousands of referenced objects.
It is also totally unnecessary to load all related records and individually remove/dereference them, when we already know that we don't want any related object to reference to base.
Here's my implementation that does not cause memory bloat and also removes all records making only one call:
class ManyToMany < Referenced::Many def nullify metadata.klass.collection.update({metadata.inverse_foreign_key => {"$in" => [base.id] }}, {"$pull" => {metadata.inverse_foreign_key => base.id}}, :multi => true) base.update_attribute metadata.key, [] end end