Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1525

In some circumstances, building and creating referenced documents fails

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.4.0
    • 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.

            Assignee:
            Unassigned Unassigned
            Reporter:
            behrangsa behrangsa
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: