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

Unexpected side effect when assigning to a belongs_to relation

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

      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@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            jon.ekdahl@gmail.com Jon Ekdahl
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: