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

Assignment of embedded association doesn't work when used before another association assignment

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 8.0.1
    • Affects Version/s: 6.4.8, 7.4.0
    • Component/s: Persistence
    • None
    • Minor Change

      Hi I noticed a strange behaviour when trying to use both `assign_attributes` and association assignment `"#{association}="` methods in the same object:

      require 'mongoid'
      require 'rspec'
      
      Mongoid.configure do |config|
        config.connect_to('mongoid_embedded_test')
      end
      
      class Post
        include Mongoid::Document
      
        embeds_many :comments
        embeds_many :tags
      end
      
      class Comment
        include Mongoid::Document
      
        field :content
        embedded_in :post
      end
      
      class Tag
        include Mongoid::Document
      
        field :content
        embedded_in :post
      end
      
      describe Post do
        let(:post) do
          Post.create!(
            comments: [Comment.new({content: 'comment 1'}), Comment.new({content: 'comment 2'})],
            tags: [Tag.new({content: 'tag 1'}), Tag.new({content: 'tag 2'})]
          )
        end
      
        it 'works' do
          post.tags = [Tag.new({content: 'tag 3'}), Tag.new({content: 'tag 4'})]
          post.assign_attributes(
            comments: [Comment.new({content: 'comment 3'}), Comment.new({content: 'comment 4'})],
          )
          post.save!
      
          fresh_post = Post.find(post.id)
      
          expect(fresh_post.tags.size).to eq(2)
          expect(fresh_post.comments.size).to eq(2)
        end
      
        it 'fails' do
          post.assign_attributes(
            comments: [Comment.new({content: 'comment 3'}), Comment.new({content: 'comment 4'})],
          )
          post.tags = [Tag.new({content: 'tag 3'}), Tag.new({content: 'tag 4'})]
          post.save!
      
          fresh_post = Post.find(post.id)
      
          expect(fresh_post.tags.size).to eq(2)
          expect(fresh_post.comments.size).to eq(2)
        end
      end
      

       

      I test this with the versions 6.4.8 and 7.4.0 and both fails.

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            rodrigorcomp@gmail.com Rodrigo R Aquino
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: