mongoid/mongoid — Issue #1718: Targets::Enumerable #first, #last - odd behavior
Author: matthewbennink
Created: 2012-02-14 17:44:23+00:00
State: open

This appears to be a result of a commit related to #1176. Specifically, if a parent document is accessed via a child document, then the `@added` array will contain the child document. This causes both #first and #last to return the child document, irregardless of the criteria. The child document appears to be added to the array during the #bind call (https://github.com/mongoid/mongoid/blob/master/lib/mongoid/relations/bindings/referenced/in.rb#L44).

I'm not sure if this is a bug or expected behavior.

To reproduce (latest master):

```
require 'rubygems'
gem 'mongoid'
require 'mongoid'

Mongoid.config.master = Mongo::Connection.new.db("test")

class Post
include Mongoid::Document
field :title
has_many :comments, :order => ["_id", :asc]
end

class Comment
include Mongoid::Document
field :body
belongs_to :post
end

post = Post.create!(title: 'Title')
first_comment = post.comments.create!(body: 'First comment.')
last_comment = post.comments.create!(body: 'Last comment.')

puts first_comment.reload.post.comments.last == last_comment # false
puts first_comment.reload.post.comments.criteria.last == last_comment # true
```