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

Association has_and_belongs_to_many reports wrong number of associated objects in some cases

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 8.0.10, 8.1.10, 9.0.6
    • Affects Version/s: 8.0.9, 8.1.9, 9.0.5
    • Component/s: Associations
    • None
    • None
    • Ruby Drivers
    • Not Needed
    • None
    • None
    • None
    • None
    • None
    • None

      Mongoid Association, has_and_belongs_to_many, reports wrong number of associated object in some cases. Issue is observed for methods size and length. Code that reproduces the issue is shown bellow.

      require "logger"
      require "mongoid"
      Mongoid.configure do |config|
        config.clients.default = {
          hosts: ['localhost:27017'],
          database: 'my_db',
          options: {
            connect: :direct  
          }
        }
        config.log_level = :warn
      end
      class Parent
        include Mongoid::Document
        has_and_belongs_to_many :children, class_name: "Child", inverse_of: :parents
      end
      class Child
        include Mongoid::Document
        has_and_belongs_to_many :parents, class_name: "Parent", inverse_of: :children
      end
      p Mongoid::VERSION
      parent = Parent.new()
      parent.save!
      parent2 = Parent.new()
      parent2.save!
      child_one = Child.new()
      child_one.parents = [parent]
      child_one.save!
      child_two = Child.new()
      child_two.parents = [parent2]
      parent_loaded = Parent.find(parent.id)
      p "BEFORE"
      p parent_loaded.children.size
      p parent_loaded.children.length
      p parent_loaded.children.count
      parent_loaded.children = [child_one, child_two]
      p "AFTER"
      p parent_loaded.children.size
      p parent_loaded.children.length
      p parent_loaded.children.count
      

      Output is

      "8.0.9"
      "BEFORE"
      1
      1
      1
      "AFTER"
      1
      1
      2 

      I would expect that all values after "AFTER" are 2. Issue can be observed in versions 8.0.X, 8.1.X and 9.0.X. Version 7.5.X seams to work fine.

      Gemfile used

       

      source 'https://rubygems.org'
      ruby '3.2.2'
      
      gem 'mongoid', '8.0.9'
      gem 'rails', '~> 6.1' 

       

      I poked around a bit, seams like issue is related to tracking of _added. When assigned like this, new item doesn't get counted as _added.

       

            Assignee:
            jamis.buck@mongodb.com Jamis Buck
            Reporter:
            boris.vukojevic@glooko.com Boris Vukojevic
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved:
              None
              None
              None
              None