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

Incorrect foreign key value set in has_many target when an orphan child is associated with parent via its id

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Critical - P2 Critical - P2
    • 8.0.1
    • Affects Version/s: None
    • Component/s: Associations
    • None
    • Minor Change

      Given a parent and child models as follows, which permit children to be created as orphans:

      class Article
        include Mongoid::Document
        has_many :comments
      end
      
      class Comment
        include Mongoid::Document
        belongs_to :article, required: false
      end
      

      When a child is created an orphan and then the parent is instantiated referencing the orphan child via comment_ids, AND the parent instantiation also specifies an explicit id, AND the explicit id is specified later in the hash than the orphan child reference, the foreign key written into the child is a generated id value and not the explicitly specified one:

      comment = Comment.create!
      
      article = Article.new(
          comment_ids: [comment.id],
          id: 1,
      )
      p article.comments
      p article
      
      [#<Comment _id: 60823adb2c97a65c19087cd1, article_id: BSON::ObjectId('60823adb2c97a65c19087cd2')>]
      #<Article _id: 1, >
      

      The correct value (1) is written into article_id if:

      • An unsaved comment is referenced instead of a saved orphan one:
      article = Article.new(
          comments: [Comment.new],
          id: 1,
      )
      
      • The id is specified first:
      article = Article.new(
          id: 1,
          comment_ids: [comment.id],
      )
      
      • The comment object is referenced instead of the comment id:
      article = Article.new(
          comments: [comment],
          id: 1,
      )
      

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: