mongoid/mongoid — Issue #1670: Two embeds_ones store only one object if class_name is same
Author: dankie
Created: 2012-02-03 15:17:38+00:00
State: open

I have a bug which sounds like

* https://github.com/mongoid/mongoid/issues/990
* https://github.com/mongoid/mongoid/issues/1444

To reproduce, use the following files (tested with Rails 3.2.1, mongoid 2.4.3, rspec 2.8.0).

Head model:

class Head
include Mongoid::Document
embeds_one :left_eye, :class_name => 'Eye', :inverse_of => :head
embeds_one :right_eye, :class_name => 'Eye', :inverse_of => :head
end

Eye model:

class Eye
include Mongoid::Document
embedded_in :head, :class_name => 'Head', :inverse_of => :left_eye
embedded_in :head, :class_name => 'Head', :inverse_of => :right_eye
field :color,
:type => String
end

The rspec test which shows the error:

describe Head do

before(:each) do
# create a new head with two eyes
@new_head = Head.create
@new_head.left_eye = Eye.create(
:head => @new_head,
:color => 'brown'
)
@new_head.right_eye = Eye.create(
:head => @new_head,
:color => 'blue'
)
end

it 'should be able to store two different colored eyses.' do
@new_head.right_eye.class.should == Eye
@new_head.left_eye.class.should == Eye
end

it 'should have eyes after reloading.' do
@new_head.reload
@new_head.right_eye.class.should == Eye
@new_head.left_eye.class.should == Eye
end

end

The output of the test is as follows:

$ bundle exec rspec spec/models/head_spec.rb
.F

Failures:

1) Head should have eyes after reloading.
Failure/Error: @new_head.right_eye.class.should == Eye
expected: Eye
got: NilClass (using ==)
Diff:
@@ -1,2 +1,2 @@
-Eye
+NilClass
# ./spec/models/head_spec.rb:31:in `(root)'

Finished in 0.119 seconds
2 examples, 1 failure

Failed examples:

rspec ./spec/models/head_spec.rb:29 # Head should have eyes after reloading.

This error occurs (if my investigations were right) since mongoid 2.2. As I mentioned above, I created a very blank rails app and followed all instructions to set up the app. Please let me know, if anyone else encounters this bug.

Thanks,
Daniel