mongoid/mongoid — Issue #1469: Eager Loading for has_one Not Behaving as Expected
Author: benzittlau
Created: 2011-12-01 18:26:53+00:00
State: open

It is possible I am not using this correctly, but I haven't been able to find much documentation about it's use. Using Mongoid 2.3.4 I'm finding that even though I do eager loading on a has_one relation, the database is still getting hit when I try to access the relation. Here are my models:

```ruby
class BookShelf
include Mongoid::Document
include Mongoid::Timestamps

has_one :book
end

class Book
include Mongoid::Document
include Mongoid::Timestamps

field :name, :default => "Test"

belongs_to :book_shelf
end
```

And here's my test case:

```
ruby-1.9.2-p180 :003 > Mongoid.identity_map_enabled
=> true
ruby-1.9.2-p180 :004 > @bookshelves = BookShelf.includes(:book).all.to_a
=> [#, #, #, #, #, #, #, #, #, #]
ruby-1.9.2-p180 :007 > Mongoid::IdentityMap.get(Book, "book_shelf_id" => @bookshelves.first.id)
=> #
ruby-1.9.2-p180 :008 > @bookshelves.first.book
=> #
```

When I execute the last call, I still see a call to the database:

```
Thu Dec 1 11:24:39 [conn37] query: mongotest_development.books{ $query: { book_shelf_id: ObjectId('4ed7b86d1dbbbb700c000001') }, $orderby: { _id: 1 } }
Thu Dec 1 11:24:39 [conn37] running multiple plans
Thu Dec 1 11:24:39 [conn37] used cursor: 0x100e31e20
Thu Dec 1 11:24:39 [conn37] query mongotest_development.books ntoreturn:1 reslen:140 nreturned:1 0ms
```

I would have expected that with eager loading and the book in the identity map that this call to the database should not occur.