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

has_and_belongs_to_many association in embedded model causes path issue

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 9.0.0, 8.1.5, 8.0.8
    • Affects Version/s: 8.0.1, 8.1.4
    • Component/s: None

      In my app I use has_and_belongs_to_many associations in embedded models – behaviour which used to work in Mongoid 7, but no longer works in Mongoid 8. I tried going through the changelog and docs, but could not find anything that seemed to indicate this behaviour should no longer work or has been changed. This seems like a bug.

      class Page
        include Mongoid::Document
        embeds_many :blocks, class_name: "Block"
      end
      
      class Block
        include Mongoid::Document
        embedded_in :page
      end
      
      class ImageBlock < Block
        has_and_belongs_to_many :attachments, inverse_of: nil
        accepts_nested_attributes_for :attachments
      end
      
      class Attachment
        include Mongoid::Document
        field :file, type: String
      end
      
      page = Page.create!
      image_block = page.blocks.build({ _type: "ImageBlock", attachments_attributes: [{ file: "foo.jpg" }] })
      
      image_block.save! # => "Mongo::Error::OperationFailure: An empty update path is not valid. (on 127.0.0.1:27017, legacy retry, attempt 1)"
      
      page.save! # => 
        "Mongoid::Errors::InvalidPath:
          message:
            Having a root path assigned for ImageBlock is invalid.
          summary:
            Mongoid has two different path objects for determining the location of a document in the database, Root and Embedded. This error is raised when an embedded document somehow gets a root path assigned.
          resolution:
            Most likely your embedded model, ImageBlock is also referenced via a has_many from a root document in another collection. Double check the association definitions and fix any instances where embedded documents are improperly referenced from other collections."
      

            Assignee:
            dmitry.rybakov@mongodb.com Dmitry Rybakov
            Reporter:
            asgerb Asger Behncke Jacobsen
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: