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

Fix primary_key option on ManyToMany relations

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.1.5
    • Affects Version/s: None
    • Component/s: None
    • None

      Consider the following relations

      class Car
        include Mongoid::Document
        field :vin, type: String
        has_and_belongs_to_many :owner, primary_key: :ssn
      end
      
      class Owner
        include Mongoid::Document
        field :ssn, type: String
        has_and_belongs_to_many :cars, primary_key: :vin
      end
      

      Queries looks up related objects by primary_key defined on the relation:

      owner = Owner.create ssn: '1234'
      car = Car.create vin: 'ABCD', owner_ids: ['1234']
      car.owners                   # returns [owner]
      

      However, inserts uses the primary_key on the base object instead

      car = Car.create vin: 'ABCD'
      owner = Owner.create ssn: '1234'
      car.owners << owner    # complains about :ssn field not defined on Car
      

      The query and binding behaviors on ManyToMany relations are inconsistent. I think the query behavior is implemented intuitively, so this seems to be a bug on bindings.

      Another issue is that car will save owner's ObjectID in its owner_ids set regardless of the primary_key field defined on either side of the relation.

      This patch attempts to solve both of these issues. MONGOID-2809 was used as a reference.

            Assignee:
            durran Durran Jordan
            Reporter:
            ukisami ukisami
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: