Moped::Errors::OperationFailure when creating an embedded object

482 Views Asked by At

I'm using mongoid 3.1.4 altogether with moped 1.5.1, mongodb 2.4.1, and ruby 1.9.3.

I have next models:

class Practice
  include Mongoid::Document
  embeds_many :distresses
end

class Distress
  include Mongoid::Document
  embedded_in :practice
end

When I do something like this it seems to be working:

practice = Practice.create
practice.distresses.create

But when I place safe: true in my config file and I do the same, then I get:

Moped::Errors::OperationFailure: The operation: #<Moped::Protocol::Command
  @length=82
  @request_id=22
  @response_to=0
  @op_code=2004
  @flags=[]
  @full_collection_name="collection.$cmd"
  @skip=0
  @limit=-1
  @selector={:getlasterror=>1, :safe=>true}
  @fields=nil>

And actually, I got the error when creating the distress in any way. This also throws the exception:

practice = Practice.create
distress = practice.distresses.build
distress.save

When I check with practice.distresses.count I can see that distresses where created successfully in the database, however I get the exception mentioned above.

1

There are 1 best solutions below

0
On

Ok, after some days I was able to fix this problem.

In my Distress model I had a before_create callback that was trying to update a field on the Practice parent object. Somehow this makes Moped to create a wrong request that makes MongoDB to fail.

I changed before_create callback for after_create and everything is working now.

Hope this helps somebody else.