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

Relations aren't updated when we set relation ids before the model id

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 7.0.12, 7.2.2
    • Component/s: None
    • Labels:
      None

      Given those models :

      class Article
        include Mongoid::Document
        has_many :comments, autosave: true
      end
      
      class Comment
        include Mongoid::Document
        belongs_to :article
      end
      

      When we create an article with comment_ids before id, the relation aren't correctly bound after reloading. Here is an example :

          comment = Comment.create
          article = Article.create(
            comment_ids: [comment.id],
            id: '123',
          )
      
          pp article.comments.count #=> 1
          pp article.comments.criteria.selector['article_id'] # => Gives a random id
          pp article.comments.context.view.count # => 1
      
          article.reload
      
          pp article.comments.count # => 0
          pp article.comments.criteria.selector['article_id'] #=> '123'
          pp article.comments.context.view.count # => 0
      

      As you can see, comments are empty after reloading. If we set the id before the comment_ids, this is correct :

          comment = Comment.create
          article = Article.create(
            id: '123',
            comment_ids: [comment.id],
          )
      
          article.reload
      
          pp article.comments.count # => 1
          pp article.comments.criteria.selector['article_id'] # => '123'
          pp article.comments.context.view.count # => 1
      

      Another interesting fact, the behavior is different with Mongoid 6 and 7, as you can see with this code where I removed autosave and do a "manual" autosave :

          comment = Comment.create
          article = Article.create(
            comment_ids: [comment.id],
            id: '123',
          )
      
          article.comments.each do |comment|
            comment.reload
            comment.update(article: article)
          end
      
          pp article.comments.count # Gives 1 with Mongoid 6.2.1 and 0 with Mongoid 7.0.12
      
          article.reload_relations
      
          pp article.comments.count # Gives 1 in both versions.
      

      The behavior should be the same if we set id after or before comments_ids.

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            guirec.corbel@gmail.com Guirec Corbel
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: