mongoid/mongoid — Issue #1544: Rename child#to_a
Author: Aupajo
Created: 2012-01-02 22:02:14+00:00
State: open

I had written a custom `to_a` method on an embedded document, without realizing that Mongoid uses `to_a` internally and expects it to work a certain way.

In this instance:

```ruby
module Mongoid #:nodoc
module Hierarchy #:nodoc
module InstanceMethods #:nodoc:

# @return [ Array ] All child documents in the hierarchy.
def _children
@_children ||=
[].tap do |children|
relations.each_pair do |name, metadata|
if metadata.embedded?
child = send(name)
child.to_a.each do |doc|
children.push(doc)
children.concat(doc._children) unless metadata.versioned?
end if child
end
end
end
end
```

When `child.to_a` is called, it expects a document to wrap itself in an array (e.g. calling `to_a` on `#` should return `[#]`.

If to_a returns anything that can't respond to `_children`, it will fail. Given that it's not that uncommon to use `to_a`, wouldn't it be better to use a different method name?