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

has_and_belongs_to_many custom primary key gets ignored when building a document or adding multiple documents

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 7.4.0
    • Affects Version/s: 7.3.3
    • Component/s: Associations
    • None
    • Fully Compatible

      As described in the summary:

      class FireHydrant
        include Mongoid::Document
        field :location, type: String
        has_and_belongs_to_many :cats, primary_key: :name
      end
      
      class Cat
        include Mongoid::Document
        field :name
        belongs_to :person, primary_key: :username
      end
      
      > fire_hydrant = FireHydrant.create(location: '221B Baker Street')
      #<FireHydrant _id: 6174ccb84aec8bea5a39ba2a, location: "221B Baker Street", dog_ids: nil, cat_ids: nil>
      > fire_hydrant.cats.build name: 'Meow'
      #<Cat _id: 6174ce0a4aec8bea5a39ba2d, name: "Meow", person_id: nil>
      > fire_hydrant.cat_ids
      [BSON::ObjectId('6174ce0a4aec8bea5a39ba2d')] # instead of ['Meow']
      > cats = [Cat.create(name: 'Kitty'), Cat.create(name: 'Kitten')]
      [#<Cat _id: 6174ccbc4aec8bea5a39ba2b, name: "Kitty", person_id: nil>, #<Cat _id: 6174ccbc4aec8bea5a39ba2c, name: "Kitten", person_id: nil>]
      > fire_hydrant.cats = cats
      [#<Cat _id: 6174ccbc4aec8bea5a39ba2b, name: "Kitty", person_id: nil>, #<Cat _id: 6174ccbc4aec8bea5a39ba2c, name: "Kitten", person_id: nil>]
      > fire_hydrant.cat_ids
      [BSON::ObjectId('6174ccbc4aec8bea5a39ba2b'), BSON::ObjectId('6174ccbc4aec8bea5a39ba2c')] # instead of ['Kitty', 'Kitten']
      

      Some codes in Mongoid::Association::Referenced::HasAndBelongsToMany uses doc._id directly, regardless of the association's primary_key.

      https://github.com/mongodb/mongoid/blob/af797ed8b3803898d20b5dc997c4f3e941b5a9a9/lib/mongoid/association/referenced/has_and_belongs_to_many/proxy.rb#L57-L62

      https://github.com/mongodb/mongoid/blob/af797ed8b3803898d20b5dc997c4f3e941b5a9a9/lib/mongoid/association/referenced/has_and_belongs_to_many/proxy.rb#L85

       

       

       

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            mit.shibuya@gmail.com Mitsuhiro Shibuya
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: