-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
I have a TeamMember class:
class TeamMember include Mongoid::Document field :name, type: String has_and_belongs_to_many :teams end
and a Team class:
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:
Team.create(member_names: "member1, member2")
However when the team member does not exit, and the control flow enters:
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.