mongoid/mongoid — Issue #1503: Mass-assignment of a has_many relationship only works for new children (unless re-assigning from a proxy)
Author: ashmoran
Created: 2011-12-15 20:23:18+00:00
State: open

This is a variant of issue #1173. I've forked the GIST @mrkurt posted and turned it into a slightly longer RSpec spec: https://gist.github.com/1482621

We ran into what we assume is a related issue. After @mrkurt's description, you just need the line

```ruby
puts "Parent has #{p.kids.count} kids"`
```

which should be 10, but actually shows 0.

The spec file `has_many_assignment_spec.rb` contains a more detailed breakdown of the problem. I've commented failing examples with the actual output. The spec file was written against Mongoid master at commit 14446089c1fb5b24987ffd4d48e1e410d5b97a86.

What appears to be happening, is that if you mass-assign a has many association, the association will only accept children that _weren't previously in the association_. Bizarrely, however, you can reassign the whole collection from a proxy (eg `Kid.all`), but not an array, (eg `Kid.all.to_a`, or `[ Kid.first ]`). Assigning a mixed array of old and new results in only the new children being added.

There are a few other situations that me and another developer have investigated experimentally, but I think this summarises the main points. (I'm fairly sure I've seen this behaviour even after disabling the identity map and reloading the parent before re-assigning children, although I can't imagine how that could go wrong.)

Unfortunately, I'm very new to Mongoid and have no idea yet what's going on underneath - I haven't read much of the association code. Can anyone confirm that this is a bug and not a misunderstanding?