Unexpected side effect when assigning to a belongs_to relation

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Duplicate
    • Priority: Major - P3
    • None
    • Affects Version/s: 6.4.4
    • Component/s: Associations
    • None
    • Environment:
      Ruby 2.6.3, Rails 5.2.3
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      Hi,

      We're seeing an somewhat unexpected side effect code that follows the pattern below. After assigning a new author object to a post, the old author object has been modified.

      require 'rails_helper'
      
      RSpec.describe 'mongoid relations' do
      
        class Post
          include Mongoid::Document
      
          belongs_to :author
        end
      
        class Author
          include Mongoid::Document
      
          field :name, type: String
        end
      
        context 'when a post gets a new author' do
          it 'does not change the old author' do
            author = Author.create!(name: "old")
            post = Post.new(author: author)
            post.save!
      
            post.reload
            expect(post.author.name).to eq("old")
      
            old_author = post.author
      
            post.author = Author.create!(name: "new")
            post.save!
      
            new_author = post.author
            expect(new_author.name).to eq("new")
            expect(old_author.name).to eq("old") # boom!
          end
        end
      end
      

      This issue looks similar to MONGOID-3999, which is still open but was reported in 2015. Feel free to close this as a duplicate if you consider it to be the same issue.

              Assignee:
              Oleg Pudeyev (Inactive)
              Reporter:
              Jon Ekdahl
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Created:
                Updated:
                Resolved: