mongoid/mongoid — Issue #1498: after_create getting called before object saved into mongo
Author: skisulli
Created: 2011-12-13 23:55:28+00:00
State: open

With mongoid 2.3.2 or greater there is a problem where the after_create callbacks (and possibly others) are called before the object is written to mongo.

We have an activity model that adds itself to a resqueue queue after creation so that we can do further processing on it. After upgrading to mongoid 2.3.4 our tests were failing because the queue perform method, and by extension the after_create callback, was getting called before the object was written to mongo.

```Ruby
class Activity
include Mongoid::Document
include Mongoid::Timestamps

field :user_id, type: Integer
field :action, type: String
field :visibility, type: Integer

after_create :add_to_activity_queue

def perform
...
end

private

def add_to_activity_queue
Resque.enqueue(self.class, self.id)
end
end
```

With a debugger in the add_to_activity_queue method right before the enqueue call the activity appeared fine. It had a created_at, id, and self.persisted? was true. But if you looked in mongo it was not persisted.

Downgrading to 2.3.1 fixed this problem.