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

Self-referencing has_and_belongs_to_many not updated properly

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 7.0.0
    • Affects Version/s: 5.1.2
    • Component/s: None
    • None

      Hi,

      I have an issue with self-referencing has_and_belongs_to_many relations.
      With the following model and test case, the last two tests fail, while I expected them to succeed:

      ```ruby
      class Item
      include Mongoid::Document

      has_and_belongs_to_many :parents, inverse_of: :children, class_name: 'Item'
      has_and_belongs_to_many :children, inverse_of: :parents, class_name: 'Item'
      end

      RSpec.describe Item, type: :model do
      describe '#create' do
      let!(:parent)

      { Item.create! }

      let!(:child)

      { Item.create(parents: [parent]) }

      before do
      parent.reload
      child.reload
      end

      it

      { expect(child.parents).to include(parent) }
      it { expect(child.parent_ids).to include(parent.id) }
      it { expect(parent.children).to include(child) }
      it { expect(parent.child_ids).to include(child.id) }

      describe '#update' do
      before do
      child.update(parents: [parent])
      end

      it { expect(child.parents).to include(parent) }

      it

      { expect(child.parent_ids).to include(parent.id) }
      it { expect(parent.children).to include(child) }
      it { expect(parent.child_ids).to include(child.id) }

      describe '#reload' do
      before do
      parent.reload
      child.reload
      end

      it { expect(child.parents).to include(parent) }
      it { expect(child.parent_ids).to include(parent.id) }

      it

      { expect(parent.children).to include(child) }

      it

      { expect(parent.child_ids).to include(child.id) }

      end
      end
      end
      end
      ```

      Thanks in advance!

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            richardm Richard Machielse
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: