mongoid/mongoid — Issue #1445: Calling include? messes up relationship
Author: averas
Created: 2011-11-22 23:51:29+00:00
State: open

I discovered this rather odd bug when I added authorization to my application. I noticed that when I added ad extra iteration on a relationship in the authorization code, strange things happened in my view - references in the relationships multiplied!

I reproduced the issue as follows:

```ruby
class Foo
include Mongoid::Document
has_and_belongs_to_many :bars, :class_name => 'Bar', :inverse_of => :foos
end
```

```ruby
class Bar
include Mongoid::Document
has_and_belongs_to_many :foos, :class_name => 'Foo', :inverse_of => :bars
end
```

```ruby
require 'mongoid'
require './foo'
require './bar'

Mongoid.database = Mongo::Connection.new('localhost','27017').db('bugs')
Mongoid.master.collections.reject { |c| c.name =~ /^system/}.each(&:drop) # Clean sheet

foo = Foo.create
foo.bars << Bar.create
puts foo.bars.count # 1, as expected

foo = Foo.first
puts foo.bars.to_a.count # 1, as expected
puts foo.bars.to_a.count # 1, as expected!

foo = Foo.first
bar = Bar.first
puts foo.bars.include?(bar) # true, as expected
puts foo.bars.to_a.count # 1, as expected
puts foo.bars.to_a.count # 2, not expected!
```