Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1504

Mass-assignment of a has_many relationship only works for new children (unless re-assigning from a proxy)

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.4.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      This is a variant of issue MONGOID-1174. 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

      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?

            Assignee:
            Unassigned Unassigned
            Reporter:
            ashmoran ashmoran
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: