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

HABTM relations return docs in the wrong order

      If you have a HABTM relation, Mongoid retrieves the related documents in the wrong order.

      This is because the $in operator is used, which causes the related documents to be sorted by using MongoDB's natural order .

      I'd expect the documents to be returned in the order that their IDs are stored in.

      This was originally reported in MONGOID-248, and fixed in rc.1 , but seems to have regressed since then.

      Here's an example that shows the bug:

      class Post
        include Mongoid::Document
      
        has_and_belongs_to_many :tags
      end
      
      class Tag
        include Mongoid::Document
      
        field :name, :type => String
      
        has_and_belongs_to_many :posts
      end
      
      Post.delete_all
      Tag.delete_all
      
      t1 = Tag.create :name => 'T1'
      t2 = Tag.create :name => 'T2'
      t3 = Tag.create :name => 'T3'
      t4 = Tag.create :name => 'T4'
      
      p = Post.create :tag_ids => [t2.id, t4.id, t1.id, t3.id]
      p.reload
      
      # The tags' order in the "tag_ids" field:
      p.tag_ids.map {|id| Tag.find(id).name}
      => ["T2", "T4", "T1", "T3"]
      
      # The tags' order from the "tags" relation:
      p.tags.map(&:name)
      => ["T1", "T2", "T3", "T4"]
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            nickh Nick Hoffman
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: