mongoid/mongoid — Issue #1524: In some circumstances, building and creating referenced documents fails
Author: behrangsa
Created: 2011-12-26 04:15:55+00:00
State: open

I have a `TeamMember` class:

```ruby
class TeamMember
include Mongoid::Document

field :name, type: String

has_and_belongs_to_many :teams
end
```
and a `Team` class:

```ruby
class Team
include Mongoid::Document

has_and_belongs_to_many :team_members

def member_names=(names)
names.split(/\s*,\s*/).each do |name|
team_member = TeamMember.first(conditions: {name: name})
if team_member
self.team_members << team_member
else
self.team_members.build(name: name)
end
end
end
end
```

As it can be seen, I am passing a string of comma separated names to the `Team`'s `create!` method using a virtual attribute to create or assign its team members:

```ruby
Team.create(member_names: "member1, member2")
```

However when the team member does not exit, and the control flow enters:

```ruby
else
self.team_members.build(name: name)
end
```

An exception is thrown:

```
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.push
```

A similar process works with both of MongoMapper and ActiveRecord. It would be nice if Mongoid could handle this scenario as well. I think at the moment Mongoid cannot create referenced documents from a call to `create!`.

I am using Mongoid 2.3.4 and Rails 3.1.3.