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

#last on a has_many relation does not return the last element

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 6.0.0
    • Affects Version/s: 5.0.0
    • Component/s: None
    • None
    • Environment:
      ruby 2.2.1, mongoid gem checked out on sha af6f359

      Mongoid version : 5.0.0, Ruby: 2.2.1, git sha : af6f359

      When a document from a class defined with a has_many relation is loaded, #last on the relation will return the first document.

      This spec should pass but it fails

      require "spec_helper"
      class Me
        include Mongoid::Document
        has_many  :drugs, dependent: :delete, validate: false
      end
      
      class Drug
        include Mongoid::Document
        belongs_to :me, counter_cache: true
      end
      
      describe Mongoid::Relations::Referenced::Many do
        describe "#last" do
          context "when a base document is loaded from database" do
            before do
              person = Me.create!
              person.drugs.create!
              person.drugs.create!
            end
      
            it "returns the expected last document" do
              person = Me.first
              expect(person.drugs.size).to eq(2)
              expect(person.drugs.last.id).to_not eq(person.drugs.first.id)
            end
          end
        end
      end
      

      The problem seems to be into Enumarable#last method, which look like at _added first and do not provide order to _unloaded (see comments on Criteria#last)

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            ajoulie Antoine Joulie
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: