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

Changing order of ids in has_and_belongs_to_many field is not saved

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

      When setting an _ids field of a has_and_belongs_to_many to a new array with the same elements as before but a different order, and then calling save, it's not persisted. When reading it later, the order is still as it was before.

      Example:

      class A
        include Mongoid::Document
        has_and_belongs_to_many :bs
      end
      
      class B
        include Mongoid::Document
      end
      

      And then:

      b1 = B.create
      b2 = B.create
      a = A.create
      a.b_ids = [b1.id, b2.id]
      a.save
      
      a.b_ids = [b2.id, b1.id]
      a.save
      
      a_reread = A.find(a.id)
      a_reread.b_ids  #=> is [b1.id, b2.id], but should be [b2.id, b1.id]
      

      When changing it directly via MongoDB shell, the order is correct (and Mongoid returns them in the new order).

      My use case is that the user ranks a bunch of entries by ordering them, which should be persisted as an array of ids in mongo. So, preserving order is kind of important in this case.

      Spec coming up.

            Assignee:
            Unassigned Unassigned
            Reporter:
            robinst robinst
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: