-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
Hi, here we have two documents Entity and EntityLink (embedded into Entity).
Running this scripts (mongoid 3.1.3) will:
- create 2 entities ("entity" and "entity_b") using Entity.create!(...)
- create an embedded EntityLink in each of the two (using entity.links.find_or_create_by(...))
- destroy the links created above with entity.links.destroy_all
- reloading the entities with entity.reload
- see the links reappear
As you can see the first test (test A) fails, while the others pass. Why?
thanks
require 'mongoid' class Entity include Mongoid::Document field :name, type: String embeds_many :links, class_name: "EntityLink" end class EntityLink include Mongoid::Document embedded_in :entity field :le, type: Moped::BSON::ObjectId field :last_seen, type: Integer end def add_link first_entity, second_entity, update_attributes = true first_link = first_entity.links.find_or_create_by(le: second_entity._id) first_link.update_attributes!(last_seen: Time.now.to_i) if update_attributes second_link = second_entity.links.find_or_create_by(le: first_entity._id) second_link.update_attributes!(last_seen: Time.now.to_i) if update_attributes end def expect exp puts exp ? 'ok' : 'FAIL' end Mongoid.load! './config_mongoid.yaml', :development puts '===test A====================================================' Mongoid.purge! entity = Entity.create!(name: 'entity') entity_b = Entity.create!(name: 'entity_b') add_link entity, entity_b expect entity.links.size == 1 entity.links.destroy_all expect entity.links.size == 0 entity.reload # this fails, why?? expect entity.links.size == 0 puts '===test B====================================================' Mongoid.purge! entity = Entity.create!(name: 'entity') entity_b = Entity.create!(name: 'entity_b') add_link entity, entity_b expect entity.links.size == 1 entity.reload entity.links.destroy_all expect entity.links.size == 0 entity.reload # using reaload before entity.links.destroy_all make this test pass expect entity.links.size == 0 puts '====test C===================================================' Mongoid.purge! entity = Entity.create!(name: 'entity') entity_b = Entity.create!(name: 'entity_b') add_link entity, entity_b, false expect entity.links.size == 1 entity.links.destroy_all expect entity.links.size == 0 entity.reload # without updating EntityLink attributes it seems to work expect entity.links.size == 0 puts '=====test D==================================================' Mongoid.purge! entity = Entity.create!(name: 'entity') entity_b = Entity.create!(name: 'entity_b') add_link entity, entity_b expect entity.links.size == 1 entity.links.where({}).destroy_all expect entity.links.size == 0 entity.reload # using entity.links.where({}).destroy_all (instead of entity.links.destroy_all) make this test pass expect entity.links.size == 0