mongoid/mongoid — Issue #1444: Possible issue when saving an multiple embedded_in
Author: hartator
Created: 2011-11-22 12:14:05+00:00
State: open

I may have found an issue when setting multiple embeds_one with the same model.

Here my models sample :

```
class Forum
include Mongoid::Document
field :location, type: String
embeds_one :admin, class_name: 'Person'
embeds_one :contact, class_name: 'Person'
end

class Person
include Mongoid::Document
field :name, type: String
embedded_in :forum, class_name: 'Forum'
end
```

When creating a new document it works as expected :

```
[137] pry(main)> forum = Forum.new
=> #
[138] pry(main)> forum.admin = Person.new name: 'admin_first_set'
=> #
[139] pry(main)> forum.contact = Person.new name: 'contact_first_set'
=> #
[140] pry(main)> forum.save
=> true
````

The BSON :

```
{
"_id" : ObjectId("4ecb8f9c304bda69a0006469"),
"admin" : {
"name" : "admin_first_set",
"_id" : ObjectId("4ecb8fb9304bda69a000646a")
},
"contact" : {
"name" : "contact_first_set",
"_id" : ObjectId("4ecb8fc7304bda69a000646b")
}
}
```

But, when updating an existing one, it persists only the first one defined (here overriding admin person with the contact person) :

```
[141] pry(main)> forum = Forum.last
=> #
[142] pry(main)> forum.admin = Person.new name: 'admin_second_update'
=> #
[143] pry(main)> forum.contact = Person.new name: 'contact_second_update'
=> #
[144] pry(main)> forum.save
=> true
```

The BSON :

```
{
"_id" : ObjectId("4ecb8f9c304bda69a0006469"),
"admin" : {
"name" : "contact_second_update",
"_id" : ObjectId("4ecb907a304bda69a000646d")
},
"contact" : {
"name" : "contact_first_set",
"_id" : ObjectId("4ecb8fc7304bda69a000646b")
}
}
```

I have tried a few things (including polymorphic embedding), with no success.