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

Inverse association not populated for HABTM when using class_name

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Minor - P4 Minor - P4
    • 8.0.1
    • Affects Version/s: None
    • Component/s: Associations
    • Minor Change
    • None
    • None
    • None
    • None
    • None
    • None

      This works;

      class Contract
        include Mongoid::Document
      
        has_and_belongs_to_many :signatures
      
        field :item, type: String
      end
      
      class Signature
        include Mongoid::Document
      
        has_and_belongs_to_many :contracts
      
        field :name, type: String
        field :year, type: Integer
      end
      
      c=Contract.create!
      s=Signature.create!(contracts:[c])
      s.contracts.first
      # => #<Contract _id: 5c5dda8e026d7c1730969846, signature_ids: [BSON::ObjectId('5c5dda9a026d7c1730969847')], item: nil>
      
      

      Note that the contract got the signature added to its signature_ids.

      Now, if both classes have class_name set, contract does not get the signature id added to its signature_ids:

      class HabtmmContract
        include Mongoid::Document
      
        has_and_belongs_to_many :signatures, class_name: 'HabtmmSignature'
      
        field :item, type: String
      end
      
      class HabtmmSignature
        include Mongoid::Document
      
        has_and_belongs_to_many :contracts, class_name: 'HabtmmContract'
      
        field :name, type: String
        field :year, type: Integer
      end
      
      contract = HabtmmContract.create!(item: 'foo')
      s=HabtmmSignature.create!(contracts: [contract], name: 'Dave', year: 2019)
      s.contracts.first
      # => #<HabtmmContract _id: 5c5dda46026d7c1730969844, signature_ids: nil, item: "foo">
      

      One therefore has to do:

            contract = HabtmmContract.create!(item: 'foo')
            contract.signatures << HabtmmSignature.create!(contracts: [contract], name: 'Dave', year: 2019)
            contract.save!
      

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved:
              None
              None
              None
              None